and implements the Set Interface In Java
class HashSet< E >
Here, E specifies the type of objects that the set holds.
hash table is used for storage. A hash table stores information by using a mechanism called hashing
, the information is stored in the form of
is used to determine a unique value, called
is then used as the index to retrieve the data associated with the key.
Point to remember in HashSet:
- HashSet doesn't allow duplicates.
- The transformation of the key into its
hash code is performed automatically and we never see the
hash code itself.
- We can't directly index the hash table without
HashSet does not define any additional methods other than the methods of its superclasses and interfaces.
HashSet does not guarantee the order of its elements.
The following are the constructors defined by
Creats a default hash set.
HashSet(Collection<? extends E> c)
Creats a hash set by using the elements of
Creats a hash set and initializes the capacity to
.(The default capacity is 16)
HashSet(int capacity, float fillRatio)
Creats a hash set and initializes both the capacity and fill ratio(also called load capacity) of the hash set from its arguments. The fill ratio must be between 0.0 and 1.0. When the number of elements is greater than the capacity, the capacity of the hash set is multiplied with the fill ratio and the hash set is expanded.
public static void main(String arg)
List<Character> characters = new ArrayList<Character>(); //
HashSet<Character> hashcharacters = new HashSet<Character>(characters); // LINE B
System.out.println("Elements in hashcharacters: " + hashcharacters); // LINE C
System.out.print("retrieving in order: "); // LINE D
for (int i = 0; i < hashcharacters.size(); i++)
System.out.print(characters.get(i) + " "); // LINE E
hashcharacters.remove('2'); // LINE F
System.out.print("Modified HashSet: " + hashcharacters); // LINE G
Elements in hashcharacters: [D, 2, A, B, C]
retrieving in order: A B C D 2
Modified HashSet: [D, A, B, C]
In the above program at
LINE A we have created an ArrayList
characters and added elements. At
LINE B we have created a HashSet
hashcharacters and added all the elements of
LINE C we are printing the elements in the
hashcharacters. We can see the output as we discussed earlier the
HashSet doesn't return the values in order when we call the
LINE D we are retrieving the elements in
hashcharcters in order. At
LINE E inside for loop we are printing the elements in
hashcharcters in order. At
LINE F we have removed the element
LINE G we are displaying the modified
THINGS TO TRY
- Create a HahsSet with the default constructor and add all the elements of characters.
- At LINE F remove the single quotes for
2 and see the output.
The program doesn't show any compilation error since the parameter to be passed for the
remove method is
integer and method checks for the value in the set if found it removes the object if not the HashSet will remain unchanged.