简体   繁体   English

指定数组列表大小和容量?

[英]Specifying Array list size and capacity?

I have created an arraylist like this我创建了一个这样的数组列表

List<Integer> i = new ArrayList<Integer>(2);

i.add(1);
i.add(2);
i.add(3);
i.add(4);

But I am not getting any exception though i have defined initial capacity as 2 why is not throwing any exception?但是我没有收到任何异常,尽管我将初始容量定义为 2 为什么不抛出任何异常? Does the List grows automatically after it reaches the mentioned capacity??列表达到上述容量后是否会自动增长?

The initial capacity isn't a limit.初始容量不是限制。 It represents how much data can be put into the list before the list has to be reallocated.它表示在必须重新分配列表之前可以将多少数据放入列表。

You aren't getting an exception because you make assumptions on behavior ... which you didn't bother to cross-check.你不会因为你对行为做出假设而得到例外......你没有费心去交叉检查。 When code doesn't behave as you expect, far too often your expectations are wrong.当代码没有按照您的预期运行时,您的期望往往是错误的。

And in such cases, you turn to the Javadoc and find:在这种情况下,您转向Javadoc并发现:

Each ArrayList instance has a capacity.每个 ArrayList 实例都有一个容量。 The capacity is the size of the array used to store the elements in the list.容量是用于存储列表中元素的数组的大小。 It is always at least as large as the list size.它始终至少与列表大小一样大。 As elements are added to an ArrayList, its capacity grows automatically.随着元素被添加到 ArrayList,它的容量会自动增长。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM