-1

Let's suppose I want to declare a List of AbstractClass, and each of its elements must be mixed children of AbstractClass, called SubClass1 and SubClass2 (which are not abstract, by the way). But I also want it of a specific size.

So I declare

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

If I add elements the to list using

list.add(new SubClass1());
list.add(new SubClass2());

are they going to be added at the end of the array or starting from index=0? In the first case, do I have to manually add elements with a loop, like this?

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());
}
riciloma
  • 1,456
  • 2
  • 16
  • 31

3 Answers3

2

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

Both. The SIZE argument to the ArrayList constructor determines its initial capacity, not its initial length. Once this ArrayList is constructed, it has a capacity of SIZE but a size of 0. The first element added will be index 0, the second will be index 1, and so on.

If you don't supply an initial capacity, there will a default initial capacity.

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

No method calls in general have to be in any loop.

rgettman
  • 176,041
  • 30
  • 275
  • 357
1

The List interface is not intended for fixed size arrays: as answered here already. You can set an initial size however.

About adding: from the official 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.

You can add multiple elements with addAll.

Nikole
  • 322
  • 3
  • 17
1

new ArrayList(SIZE) will not limit your list to SIZE element, but will just initialize its inner array responsible for storing elements to length equal to SIZE. But it doesn't mean that later this list will not be able to store more than SIZE elements, because it still can later create new larger array with old elements and use it internally.

In other words returned list is still resizeable. It is also empty at start (its size() is 0) so there is no reason for add to start adding elements on other indexes than 0.

Pshemo
  • 122,468
  • 25
  • 185
  • 269