Reputation: 139
I was trying to initialize an ArrayList in a constructor, and I have something like this:
public class A {
private ArrayList<Items> _items = null;
private ArrayList<Items> _collection = null;
public A(int size1, int size2) {
this._items = new ArrayList<Items>(size1 * size2);
}
public void create(int size) {
this._collection = new ArrayList<Items>(size);
}
But when I tried to add something to the _items ArrayList, I was getting ArrayIndexOutOfBoundsException. Could you explain this, please? I was searching for it and added this._items
instead of _items
. I thought I going out of borders, but I tried to print _items.size
and was getting 0
, instead of size1 * size2
...
I left the ArrayList = null
because the size depends on the size1/size2 coming from the constructor
Upvotes: 3
Views: 295
Reputation: 14709
Here's the source from ArrayList
:
The constructor:
public ArrayList(int initialCapacity)
{
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
this.elementData = new Object[initialCapacity];
}
You called add(int, E)
:
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacity(size+1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1, size - index);
elementData[index] = element;
size++;
}
add
calls rangeCheckForAdd(int)
:
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
It may be subtle, but when you called the constructor, despite initializing an Object[]
, you did not initialize size
. Hence, from rangeCheckForAdd
, you get the IndexOutOfBoundsException
, since size
is 0.
All you did by passing the argument to the constructor was set the capacity, which sets the size of the array that backs the ArrayList
.
Instead of using add(int, E)
, you can use add(E e)
and this won't occur.
Upvotes: 2
Reputation: 1902
You should read the javadocs for this. size is not about 'how much the list can store' but about 'how many objects is it holding when the size was called'.
Since Lists (and for that matter any collection) are designed to grow dynamically with data being put into them, so it makes no sense to ask for the capacity of the list. If you are interested in capacity related introspection you should work with arrays instead.
Lists follow simple philosophical operations add an object, get an object, remove an object and iterate over all objects.
Upvotes: 0