119. Converting a collection into an array

In order to convert a collection into an array, we can rely on the Collection.toArray() method. Without arguments, this method will convert the given collection into an Object[], as in the following example:

List<String> names = Arrays.asList("ana", "mario", "vio");
Object[] namesArrayAsObjects = names.toArray();

Obviously, this is not entirely useful since we are expecting a String[] instead of Object[]. This can be accomplished via Collection.toArray​(T[] a) as follows:

String[] namesArraysAsStrings = names.toArray(new String[names.size()]);
String[] namesArraysAsStrings = names.toArray(new String[0]);

From these two solutions, the second one is preferable since we avoid computing the collection size.

But starting with JDK 11, there is one more method dedicated to this task, Collection.toArray​(IntFunction<T[]> generator). This method returns an array containing all the elements in this collection, using the generator function provided to allocate the returned array:

String[] namesArraysAsStrings = names.toArray(String[]::new);

Next to the fixed-size modifiable Arrays.asList(), we can build an unmodifiable List/Set from an array via the of() methods:

String[] namesArray = {"ana", "mario", "vio"};

List<String> namesArrayAsList = List.of(namesArray);
Set<String> namesArrayAsSet = Set.of(namesArray);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.160.181