Copy all elements of Java HashSet to an Object Array

Java 8Object Oriented ProgrammingProgramming

Declare a HashSet and add elements −

Set<Integer> hs = new HashSet<Integer>();
hs.add(15);
hs.add(71);
hs.add(82);
hs.add(89);
hs.add(91);
hs.add(93);
hs.add(97);
hs.add(99);

To copy all the elements, use the toArray() method −

Object[] obArr = hs.toArray();

The following is an example to copy all elements to HashSet to an object array −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      Set<Integer> hs = new HashSet<Integer>();
      hs.add(15);
      hs.add(71);
      hs.add(82);
      hs.add(89);
      hs.add(91);
      hs.add(93);
      hs.add(97);
      hs.add(99);
      System.out.println("Elements in set = "+hs);
      System.out.println("Copying all elements...");
      Object[] obArr = hs.toArray();
      for (Object ob : obArr)
      System.out.println(ob);
   }
}

Output

Elements in set = [97, 82, 99, 71, 89, 91, 93, 15]
Copying all elements...
97
82
99
71
89
91
93
15
raja
Published on 10-Jan-2019 14:03:01
Advertisements