Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert elements in a HashSet to an array in Java
First, create a HashSet and elements to it −
HashSet hs = new HashSet();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
hs.add("K");
Let us now convert the above HashSet to an array −
Object[] ob = hs.toArray();
The following is an example to convert elements in a HashSet to an array −
Example
import java.util.*;
public class Demo {
public static void main(String args[]) {
// create a hash set
HashSet hs = new HashSet();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
hs.add("K");
hs.add("M");
hs.add("N");
System.out.println("Elements in the set: "+hs);
Object[] ob = hs.toArray();
System.out.println("Converting elements to array...");
for (int i = 0; i < ob.length; i++) {
System.out.println(ob[i]);
}
}
}
Output
Elements in the set: [A, B, C, D, E, F, K, M, N] Converting elements to array... A B C D E F K M N
Advertisements