gpt4 book ai didi

java - ensureCapacity 在 Java 中如何工作?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:46:00 26 4
gpt4 key购买 nike

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());

最佳答案

契约(Contract)states the following :

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:

  • The minimumCapacity argument.
  • Twice the old capacity, plus 2.

因此,解释一下程序的输出:

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)

关于java - ensureCapacity 在 Java 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26098281/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com