In Java 8, why is the default capacity of ArrayList now zero?

Technically, it’s 10, not zero, if you admit for a lazy initialisation of the backing array. See: public boolean add(E e) { ensureCapacityInternal(size + 1); elementData[size++] = e; return true; } private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); } where /** * Default initial capacity. */ … Read more

ArrayIndexOutOfBoundsException when using the ArrayList’s iterator [duplicate]

Am I doing that right, as far as iterating through the Arraylist goes? No: by calling iterator twice in each iteration, you’re getting new iterators all the time. The easiest way to write this loop is using the for-each construct: for (String s : arrayList) if (s.equals(value)) // … As for java.lang.ArrayIndexOutOfBoundsException: -1 You just … Read more

What is the ideal growth rate for a dynamically allocated array?

I remember reading many years ago why 1.5 is preferred over two, at least as applied to C++ (this probably doesn’t apply to managed languages, where the runtime system can relocate objects at will). The reasoning is this: Say you start with a 16-byte allocation. When you need more, you allocate 32 bytes, then free … Read more