Set to Array Java

Set to Array Java


It is required in Java coding, sometimes, to convert a set to array and array to set and also list to array and array to list.
Following code on Set to Array gives two ways of converting Java set to array.

Set to Array

String[] numWordsArray = numWords.toArray(new String[numWords.size()]);

Creating a string array with the size of the elements of the set and pass it to the toArray() method. The toArray() method returns an array with the same elements of the set.

Object objectNum[] = numList.toArray();

toArray() is a method of Collections interface which returns an array with the following signature.

Object[] toArray(): Returns an array of objects containing all the elements of the collection.

Being the method of Collection interface (super interface of all DS of Java), the method can convert any DS elements into an array.

To print the array elements, toString() method of Arrays class is used.

Why System.out.println(numWords); prints the elements of Set and
why System.out.println(numWordsArray); prints some strange value with LJava and @ symbol and not the elements of array (see the output screen). For this you must have a through knowledge of toString() method of Object class.

1. Learn how to convert list to array.
2. Learn how to convert array to list.

Leave a Reply

Your email address will not be published. Required fields are marked *