CodesJava

Easy learning with example program codes

HashSet in java


HashSet:

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

HashSet example:

HashSetTest.java

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
 
/**
 * This class is used to show the HashSet functionality.
 * @author codesjava
 */
public class HashSetTest {
	public static void main(String args[]){
		//Create HashSet object.
		Set hashSet = new HashSet();
 
		//Add objects to the HashSet.
		hashSet.add("Roxy");
		hashSet.add("Sunil");
		hashSet.add("Sandy");
		hashSet.add("Munish");
		hashSet.add("Pardeep");
 
		//Print the HashSet object.
		System.out.println("HashSet elements:");
		System.out.println(hashSet);
 
		//Print the HashSet elements using iterator.
		Iterator iterator=hashSet.iterator();
		System.out.println("HashSet elements using iterator:");
		while(iterator.hasNext()){  
		   System.out.println(iterator.next());  
		}  
	}
}

Output

HashSet elements:
[Sandy, Pardeep, Munish, Sunil, Roxy]
HashSet elements using iterator:
Sandy
Pardeep
Munish
Sunil
Roxy

Download this example.
 
Next Topic: LinkedHashSet in java with example.
Previous Topic: Collection classes in java with example.



Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap