The following code example demonstrates An Example of Using HashSet in Java.

Basically, HashSet works very fast because it uses hashcodes. However, we can not predict the order of elements in a HashSet collection.

import java.util.HashSet;
import java.util.Iterator;

public class HashSetDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		HashSet<Integer> hash=new HashSet<Integer>();
		hash.add(45);
		hash.add(12);
		hash.add(4);
		hash.add(145);
		hash.add(405);
		hash.add(38);

		System.out.println("Elements in the HashSet: ");
		Iterator it=hash.iterator();
		while(it.hasNext())
		{
			System.out.println(it.next()+" ");
		}	
	}
}

Output

Demonstrating An Example of Using HashSet in Java
Demonstrating An Example of Using HashSet in Java

Further Reading

30+ Basic Java Programs

Java Practice Exercise

programmingempire

Princites