Define HashSet Class
By Ramakrishna on Mar 24, 2009 in Define HashSet
HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage. As most readers likely know, a hash table stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code. The hash code is then used as the index at which the data associated with the key is stored. The transformation of the key into its hash code is performed automatically, you never see the hash code itself. Also, your code can’t directly index the hash table. The advantage of hashing is that it allows the execution time of basic operations, such as add(), contains(), remove(), and size, to remain constant even for large sets,
The following constructors are defined:
HashSet()
HashSet(Collection c)
HashSet(int capacity)
HashSet(int capacity, float fillRatio)
The first form constructs a default has set. The second form initializes the hash set by using the elements of c. The third form initializes the capacity of the hash set to capacity. The fourth form initializes both the capacity and the fill ration (also called load capacity) of the hash set from its arguments. The fill ratio must be between 0.0 and 1.0, and it determines how full the hash set can be before it is re sized upward. Specifically when the number of elements is greater than the capacity of the hash set multiplied by its fill ratio, the hash set is expanded. For constructors that do not take a fill ratio, 0.75 is used.
HashSet does not define any additional methods beyond those provided by its superclasses and interfaces.
Importantly, note that a hash set does not guarantee the order of its elements, because the process of hashing doesn’t usually lend itself to the creation of sorted sets. If you need sorted storage, then another collection, such as TreeSet, is a better choice.
Here is an example that demonstrates HashSet:
//Demonstrate HashSet.
import java.util.*;
class HashSet Demo {
public static void main(String args[])
{
//create a hash set
HashSet hash=new HashSet();
//add elements to the hash set
hash.add(“B”);
hash.add(“A”);
hash.add(“D”);
hash.add(“E”);
hash.add(“C”);
hash.add(“F”);
System.out.println(hash);
}
}
The following is the output from this program:
[ A,F, E, D, C, B]
As explained , the elements are not stored in sorted order, and the precise output may vary.
