问题描述
考虑这个示例code:
列表<串GT; myList中=新的ArrayList<串GT;(7);
myList.add(5,你好);
myList.removeAll(Collections.singleton(NULL));的System.out.println(myList.size()+对象:);
对于(一个String:myList中){
的System.out.println(\\ t+ S);
}
myList中
与7的初始容量初始化,则下一行尝试添加字符串Hello在位置5。这将引发IndexOutOfBoundsException异常:
I looked over this question about what "initial capacity" means in terms of an ArrayList. I understand that this particular constructor is allocating room for 7 String elements, and if we try to add 8 elements to the list it'll have to allocate more room.
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]
. 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?
That would be useful in some cases... and not useful in others. Quite often you have an upper bound of the size of list you're going to create (or at least a guess) but then you populate it... and you don't want to have a list which then has the wrong size... so you'd have to maintain an index while you "set" values, and then set the size afterwards.
No, it's really not. It's a list which can be resized and uses an array behind the scenes. Try not to think of it as an array.
You do have space for 7 string references. The buffer size (i.e. the capacity) is at least 7, but the logical size of the list is still 0 - you haven't added anything to it. It's like you've got a sheet of paper that's long enough for 7 lines, but you haven't written anything yet.
If you want a prefilled list, you can easily write a method to create one:
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);
}
}
这篇关于ArrayList的初始容量和IndexOutOfBoundsException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!