Copy all elements from HashSet to Array

Q. Write a program to copy all elements from HashSet to an Array.

Answer:

The HashSet class implements the Set interface. The hashSet doesn’t allow to insert duplicate values in the list.

Copy_Elements.java

import java.util.*;
class Copy_Elements
{
        public static void main(String[] args)
        {
                HashSet<String> hs = new HashSet<String>();
                hs.add("Java");
                hs.add("APS.NET");
                hs.add("SQL");
                hs.add("Oracle");
                hs.add("PHP");
                System.out.println("HashSet elements: ");
                System.out.println(hs);

                String[] strArr = new String[hs.size()];
                hs.toArray(strArr);
                System.out.println("==================================");
                System.out.println("\nHashSet elements are copied into Array: ");

                for (String str : strArr)
                {
                        System.out.println(str);
                }
        }
}


Output:

copy hashset