java util HashSet Class - java.util.HashSet Class in Java
HashSet Class in Java
The Java Collection Framework introduces the HashSet collection. This implementation is backed by a hash table (HashMap, actually) for storing unique elements. The backing hash table ensures that duplicate elements are avoided as each element is stored and retrieved through its hash code, providing constant retrieval time.
It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. Most of the HashSet functionality is provided through the AbstractCollection and AbstractSet superclasses, which HashSet shares with TreeSet.
Is HashSet Thread Safe ?
The HashSet is not synchronized. If multiple threads access a hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set.
To prevent accidental unsynchronized access to the set, you should create set with Collections.synchronizedSet method.
What is the Performance a HashSet in Java ?
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. Iterating over this set requires time proportional to the sum of the HashSet instance's size (the number of elements) plus the "capacity" of the backing HashMap instance (the number of buckets). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.
In this tutorial you can learn about java.util.HashSet class and its examples. And also learn how to use java.util.HashSet class.
java.util.HashSet class Example
The following example shows how to use HashSet with Iterator.
How to use HashSet with Iterator
The following example shows how to use HashSet with Arrays, Set and Iterator.
How to use HashSet with Arrays, Set and Iterator
java.util.HashSet class Example 4
The following example shows how to compare two Set Collections.
How to compare two Set Collections
The following example shows how to save Set Collection into file.
How to save Set Collection into file
The following example shows how to retrieve Set Collection from file.
How to retrieve Set Collection from file