- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- Convert array to HashSet in Java
- Convert an ArrayList to HashSet in Java
- Copy all elements of Java HashSet to an Object Array
- Convert HashSet to TreeSet in Java
- Add elements to HashSet in Java
- Remove all elements from a HashSet in Java
- Convert a Vector to an array in Java
- Java Program to convert HashSet to Enumeration
- C++ Program to Convert Array to Set (Hashset)
- Iterate through elements of HashSet in Java
- Remove duplicate elements in Java with HashSet
- Convert LinkedList to an array in Java
- Count the number of elements in a HashSet in Java
- How to convert an array to a list in Java?
- How to convert an Array to a Set in Java?

Advertisements