Construct a typed Array via List.toArray() with correct size
When we construct an typed Array out of an existing List, we use the method T[] toArray(T[] a)
. When an array with a lower size than the size of the List is passed as argument, this results in a new array being created. Take a look at the implementation of ArrayList here. Using the method with an incorrect sized array is inefficient. Using the toArray
method directly with a correctly sized array is therefore preferable.
Not preferred
ArrayList myList; //Assume myList has some added entries
//Size is too small a 2nd array will be created
MyClass[] arr = myList.toArray(new MyClass[0]);
Preferred 1
ArrayList myList; //Assume myList has some added entries
//Create a correctly sized array.
MyClass[] arr = myList.toArray(new MyClass[myList.size()]);
Preferred 2
private static final MyClass[] EMPTY_ARRAY = new MyClass[0];
//Pass in the same static each time. More effective when myList is empty.
MyClass[] arr = myList.toArray(EMPTY_ARRAY);
N.B.: This blog is written based on this stackoverflow entry. All credits go to the stackoverflow poster and commentators of this entry.