CodesJava

Easy learning with example program codes

how to convert a hashset to an array in java?


Hashtable:

HashSet extends AbstractSet and implements the Set interface. It not maintains any order for its elements. It uses hash table for storage.

We can use toArray() method to convert a hashset to an array in java.

Example:

package com.codesjava;
 
import java.util.HashSet;
 
public class Test {	 
    public static void main(String[] args) {
    	//Create HashSet object
    	HashSet<String> hashSet = new HashSet<String>();
        //Add elements to HashSet
    	hashSet.add("Jai");
    	hashSet.add("Mahesh");
    	hashSet.add("Vivek");
    	hashSet.add("Naren");
    	hashSet.add("Vishal");
    	hashSet.add("Hemant");
    	System.out.println("HashSet: " + hashSet);
    	String[] strArray = new String[hashSet.size()];
    	hashSet.toArray(strArray);
        System.out.println("Array created:");
        for(String str:strArray){
             System.out.println(str);
        }
    }
}

Output

HashSet: [Naren, Jai, Vivek, Hemant, Mahesh, Vishal]
Array created:
Naren
Jai
Vivek
Hemant
Mahesh
Vishal
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki