Copy all elements of Java HashSet to an Object Array


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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 25-Jun-2020

210 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements