INTRODUCTION TO JAVA HASHSET
- The Java HashSet class implements the Set interface.
- It makes no guarantee that the order of elements will remain constant over time.
- This class is not synchronized and permits a null element.
- This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets.
- To prevent unsynchronized access to the Set: Set s = Collections.synchronizedSet(new HashSet(…));
Below is a HashSet Example showing how collections are manipulated using a HashSet
JAVA HASHSET EXAMPLE
import java.util.*;
public class HashSetExample {
private static String names[] = { "bob", "hemanth", "hhh", "hero",
"shawn", "bob", "mike", "Rick", "rock", "hemanth", "mike",
"undertaker" };
public static void main(String args[]) {
ArrayList aList;
aList = new ArrayList(Arrays.asList(names));
System.out.println("The names elements " + aList);
HashSet ref = new HashSet(aList); // create a HashSet
Iterator i = ref.iterator();
System.out.println();
System.out.print("Unique names are: ");
while (i.hasNext())
System.out.print(i.next() + " ");
System.out.println();
}
}
Output
The names elements [bob, hemanth, hhh, hero, shawn, bob, mike, Rick, rock, hemanth, mike, undertaker]
Unique names are: hhh hero bob Rick shawn hemanth rock mike undertaker