Curiosity newArrayList (E ... elements) in google guava lib

This code is a simple guava library code.

I simplified the simplified reading, the original code see => link

// Case A public static <E> ArrayList<E> newArrayList(E... elements) { int capacity = computeArrayListCapacity(elements.length); ArrayList<E> list = new ArrayList<E>(capacity); Collections.addAll(list, elements); return list; } static int computeArrayListCapacity(int arraySize) { long value = 5L + arraySize + (arraySize / 10); if (value > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } if (value < Integer.MIN_VALUE) { return Integer.MIN_VALUE; } return (int) value; } 

Why set the capacity to 5L + arraySize + (arraySize / 10) ?

And what is different between 3 cases (A, B, C)?

 //Case B public static <E> ArrayList<E> newArrayList(E... elements) { ArrayList<E> list = new ArrayList<E>(elements.length); Collections.addAll(list, elements); return list; } //Case C public static <E> ArrayList<E> newArrayList(E... elements) { ArrayList<E> list = new ArrayList<E>(); Collections.addAll(list, elements); return list; } 
+4
source share
1 answer

Nothing to add to Matthias's comment:

Case A is optimal when the list grows later, but not by much: less than 10% plus 5 more elements. If he never grows up, you lose your memory. If it grows larger, some sort of resizing will occur, but in general no one can do it.

Case B is optimal in the unbelievable case when the list is not growing. But this is unlikely, since an ImmutableList is usually used.

Case C first allocates an array of 10 elements, which can then be replaced several times in Collections.addAll . IIUIC this happens twice for elements.length==16 (namely 10 -> 15 -> 22 , since the ArrayList growth factor is 1.5).

+3
source

All Articles