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.
import java.util.*;
public class SetToArray
{
  public static void main(String args[]) 
  {                      // creating set object and adding elements
    Set numWords = new HashSet();
    numWords.add("one");
    numWords.add("two");
    numWords.add("three");
    numWords.add("four");
    System.out.println(numWords);

		                              // converting set to array
    String[] numWordsArray = numWords.toArray(new String[numWords.size()]);
    System.out.println(Arrays.toString(numWordsArray));

    System.out.println(numWordsArray);

                         // another way of conversion using asList() method, a little bit round about way
    List numList = new ArrayList (numWords);
    Object objectNum[] =  numList.toArray();

    System.out.println(Arrays.toString(objectNum));
			                      // to print using new for loop
    for (Object obj : objectNum) 
    {
      System.out.print(obj + " ");
    }
  }
}

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 Comment

Your email address will not be published.