Java The HashSet Class
Java The HashSet Class
HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage.
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.
HashSet( )
1
This constructor constructs a default HashSet.
HashSet(Collection c)
2
This constructor initializes the hash set by using the elements of the collection c.
HashSet(int capacity)
3 This constructor initializes the capacity of the hash set to the given integer value capacity. The capacity grows automatically
as elements are added to the HashSet.
This constructor initializes both the capacity and the fill ratio (also called load capacity) of the hash set from its arguments.
4
Here the fill ratio must be between 0.0 and 1.0, and it determines how full the hash set can be before it is resized 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.
Apart from the methods inherited from its parent classes, HashSet defines following methods −
boolean add(Object o)
1
Adds the specified element to this set if it is not already present.
void clear()
2
Removes all of the elements from this set.
Object clone()
3
Returns a shallow copy of this HashSet instance: the elements themselves are not cloned.
boolean contains(Object o)
4
Returns true if this set contains the specified element.
boolean isEmpty()
5
Returns true if this set contains no elements.
https://www.tutorialspoint.com/java/java_hashset_class.htm 1/2
8/15/2017 Java The HashSet Class
6 Iterator iterator()
boolean remove(Object o)
7
Removes the specified element from this set if it is present.
int size()
8
Returns the number of elements in this set (its cardinality).
Example
The following program illustrates several of the methods supported by HashSet −
import java.util.*;
public class HashSetDemo {
Output
[A, B, C, D, E, F]
Advertisements
https://www.tutorialspoint.com/java/java_hashset_class.htm 2/2