gpt4 book ai didi

java - ArrayList 初始容量和 IndexOutOfBoundsException

转载 作者:IT老高 更新时间:2023-10-28 20:28:37 24 4
gpt4 key购买 nike

考虑这个示例代码:

List<String> myList = new ArrayList<String>(7);
myList.add(5, "Hello");
myList.removeAll(Collections.singleton(null));

System.out.println(myList.size() + " objects:" );
for (String s : myList) {
System.out.println("\t" + s);
}

myList以初始容量 7 进行初始化,然后下一行尝试在位置 5 处添加字符串“Hello”。这将引发 IndexOutOfBoundsException:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 0

我查看了this question关于 ArrayList 中“初始容量”的含义。我知道这个特定的构造函数正在为 7 个 String 元素分配空间,如果我们尝试将 8 个元素添加到列表中,它将不得不分配更多空间。

理解的是为什么它不创建一个大小为 7 的“空”列表,每个索引处都有空值,类似于我们声明 String[] myArray = new String[7] 时会发生的情况。 .我记得了解到 ArrayList 是 Java 对动态数组的实现,所以我期待类似的行为。如果我在声明 new ArrayList<String>(7) 时实际上没有分配 7 个字符串的空间,到底发生了什么?

最佳答案

What I don't understand is why it doesn't create an "empty" list of size 7, with null values at each index, similar to what would happen if we declared String[] myArray = new String[7].

这在某些情况下很有用……而在其他情况下则没有用。很多时候你有一个列表大小的上限你要创建(或者至少是一个猜测)但是你填充它......而你没有 em> 想要有一个大小错误的列表......所以你必须在“设置”值时维护一个索引,然后再设置大小。

I recall learning that ArrayList is Java's implementation of a dynamic array, so I'd expect a similar sort of behavior.

不,真的不是。这是一个可以调整大小的列表,并且在幕后使用一个数组。尽量不要把它想象成一个数组。

If I don't actually have space for 7 Strings allocated when I declare new ArrayList<String>(7), what is actually happening?

有7个字符串引用的空间。 buffer 大小(即容量)至少为 7,但列表的 logical 大小仍为 0 - 您还没有向其中添加任何内容。这就像你有一张足够长 7 行的纸,但你还没有写任何东西。

如果您想要一个预填充列表,您可以轻松编写一个方法来创建一个:

public static List<T> createPrefilledList(int size, T item) {
ArrayList<T> list = new ArrayList<T>(size);
for (int i = 0; i < size; i++) {
list.add(item);
}
return list;
}

关于java - ArrayList 初始容量和 IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11908037/

24 4 0