EnsureCapacity如何在Java中工作? [英] How does ensureCapacity work in Java?

查看:157
本文介绍了EnsureCapacity如何在Java中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

StringBuffer buff1 = new StringBuffer("tuts point");

System.out.println("Old Capacity of buff1 = " + buff1.capacity());
buff1.ensureCapacity(28);
System.out.println("New Capacity of buff1 = " + buff1.capacity());

StringBuffer buff2 = new StringBuffer("compilejksde");

System.out.println("Old Capacity of buff2= " + buff2.capacity());
buff2.ensureCapacity(75);
System.out.println("New Capacity of buff2= " + buff2.capacity());


推荐答案

合约说明以下内容


确保容量至少等于指定的最小值。
如果当前容量小于参数,则分配一个具有更大容量的新内部
数组。新的容量是
较大的:

Ensures that the capacity is at least equal to the specified minimum. If the current capacity is less than the argument, then a new internal array is allocated with greater capacity. The new capacity is the larger of:


  • minimumCapacity参数。

  • 两次旧容量加上2.

因此,要解释程序的输出:

So, to explain the output from your program:

Old Capacity of buff1 = 26
New Capacity of buff1 = 54  // Old capacity*2+2 (since it's larger than the argument: 28)
Old Capacity of buff2= 28
New Capacity of buff2= 75   // the argument you gave, 75 (since it's larger than 2*28+2 = 58)

这篇关于EnsureCapacity如何在Java中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆