Friday 27 July 2012

Convert HashSet to Array in Java


This Java Example shows how to convert Java HashSet object to an array using toArray method.


import java.util.HashSet;
import java.util.Set;

public class ConvertHashSetToArrayExample {

 public static void main(String[] args) {

  // create an HashSet object

  Set< string > set = new HashSet< string >();

  // Add elements to the set

  set.add("India");
  set.add("Switzerland");
  set.add("Italy");
  set.add("France");

  System.out.println("HashSet contains...");

  // display elements of HashSet

  for (String cnt : set)
   System.out.println(cnt);

  /**
   * Object[] toArray() - Returns an Object class array containing all of
   * the elements in this set.Note that we can't explicitly cast the
   * returned array to some other class type.
   **/
  Object[] countries = set.toArray();

  System.out.println("Content of array countries=");

  for (Object c : countries) {
   System.out.println(c);
  }
  /**
   * Object[] toArray(Object[] a) - Returns an array containing all of the
   * elements in this set; the runtime type of the returned array is that
   * of the specified array.
   **/

  String[] countries1 = set.toArray(new String[set.size()]);

  System.out.println("Content of array countries1=");

  for (String c : countries1) {
   System.out.println(c);
  }

 }
}


The output is:



HashSet contains...
France
Italy
Switzerland
India
Content of array countries=
France
Italy
Switzerland
India
Content of array countries1=
France
Italy
Switzerland
India

No comments:

Post a Comment