While working on ArrayList
, I found after setting the initial size of array using the constructor with initialCapacity
, then use set()
will throw an exception although the array is created, but size isn't set correctly.
Using ensureCapacity()
won't work either because it is based on the elementData
array instead of size
.
There are other side effects because of the static DEFAULT_CAPACITY
with ensureCapacity()
.
The only way to make this work is to use add() as many time as required after using the constructor.
Please check the code below.
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List test = new ArrayList(10);
test.set(5, "test");
System.out.println(test.size());
}
I am not sure why java is throwing this exception.
Behaviour I expected: test.size()
should return 10 and set(5, ...) should work.
ACTUAL: throws an Exception IndexOutOfBoundsException
.
So is it set method that is causing problem ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…