I have been thinking that LinkedList
fills faster than ArrayList
. As I know ArrayList
is based on simple array with limited length(constant). So every time array is out of range, new array with higher range will be created. LinkedList
is much simpler. It hasn't got any limit (except for memory), so it should be filled faster. But I run next code:
public static void main(String[] args) {
int length = 7000000;
List<Integer> list = new LinkedList<Integer>();
long oldTime = System.currentTimeMillis();
for (int i = 0; i < length; i++) {
list.add(i);
}
System.out.println("LinkedList fill: " + (System.currentTimeMillis() - oldTime));
list = new ArrayList<Integer>();
oldTime = System.currentTimeMillis();
for (int i = 0; i < length; i++) {
list.add(i);
}
System.out.println("ArrayList fill: " + (System.currentTimeMillis() - oldTime));
}
The output is:
LinkedList fill: 3936
ArrayList fill: 628
Why so?