关于在 Java 中声明新列表

About declaring a new List in Java

假设我要声明一个 List of AbstractClass,它的每个元素都必须是 AbstractClass 的混合子元素,称为 SubClass1SubClass2(它们不是抽象的,顺便说一句)。但我也想要它特定大小。

所以我声明

List <AbstractClass> list = new ArrayList <AbstractClass> (SIZE);

如果我使用

添加元素到列表
list.add(new SubClass1());
list.add(new SubClass2());

它们是要添加到数组的末尾还是从索引=0开始? 第一种情况,我是不是必须像这样用循环手动添加元素?

List <AbstractClass> list = new ArrayList <AbstractClass> (); //I've removed size
for(int i=0;i<SIZE;i++){
list.add(new SubClass1());
list.add(new SubClass2());
}

List 接口不适用于固定大小的数组:answered 已在此处说明。但是,您可以设置初始大小。

关于添加:来自官方Java 7 List docs

The user of this interface has precise control over where in the list each element is inserted.

add(E e) – Appends the specified element to the end of this list.

add(int index, E element) – Inserts the specified element at the specified index in this list.

您可以使用 addAll 添加多个元素。

are they going to be added at the end of the array or starting from index=0?

两者都有。 ArrayList 构造函数的 SIZE 参数决定了它的初始容量,而不是它的初始长度。一旦这个 ArrayList 被构建,它的容量为 SIZE 但大小为 0。第一个元素 added 将是索引 0,第二个元素将是索引 1,依此类推。

如果您不提供初始容量,则会有一个默认的初始容量。

In the first case, do I have to manually add elements with a loop, like this?

一般情况下,方法调用不必在任何循环中。

new ArrayList(SIZE) 不会将您的列表限制为 SIZE 个元素,而只会初始化其负责存储元素的内部数组,使其长度等于 SIZE。但这并不意味着以后这个列表将不能存储超过 SIZE 个元素,因为它以后仍然可以用旧元素创建新的更大的数组并在内部使用它。

换句话说,返回的列表仍然可以调整大小。它在开始时也是 empty(它的 size() 是 0)所以 add 没有理由开始在 0 以外的其他索引上添加元素.