Tuesday, October 22, 2013

Converting between Collections and Arrays

Collections framework was created long after the large portion of Java Platform API was designed. As a result, we occasionally need to convert between traditional arrays and more modern Collections.

Below are two methods which acts as bridge between array-based and collection-based APIs.
Array to Collections

Arrays.asList(..) is used for this

String[] arrayValues =  ...;

HashSet values = new HashSet<>(Arrays.asList(arrayValues));


Collections to Array

toArray() method - variant 1
result is an array of Objects. You cannot change its type even if we know the type of the objects in collections. This will allocate a new array even if the collection is backed by array so it will be "safe" in that no references to it are maintained by this collection.


Object[] arrayValues = values.toArray(); 

String[] arrayValues = (String[]) values.toArray(); // Error  

toArray(...) method - variant 2
result is an array containing all the elements in collection. The type of the returned array is that of the specified array. If the collection elements fits in the specified array size, it is returned. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection. 
If this collection fits in the specified array with room to spare (i.e., the array has more elements than this collection), the element in the array immediately following the end of the collection is set to null. (This is useful in determining the length of this collection only if the caller knows that this collection does not contain any null elements.) 


String[] arrayValues =  value.toArray(new String[0]); // creates new array

String[] arrayValues =  value.toArray(value.size()); // no new array is created

No comments: