HashSet
- The underlying data structure is Hashtable.
- Insertion order is not preserved and it is based on hash code of the objects.
- Duplicate objects are not allowed.
- If we are trying to insert duplicate objects we won’t get compile time error and runtime error add() method simply returns false.
- Heterogeneous objects are allowed.
- Null insertion is possible.(only once)
- Implements Serializable and Cloneable interfaces but not RandomAccess.
- HashSet is best suitable, if our frequent operation is “Search”.
Constructors
1. HashSet h = new HashSet()
Creates an empty HashSet object with default initial value 16 and default fill ratio 0.75
2. HashSet h = new HashSet(int initialcapacity)
3. HashSet h = new HashSet(int initialCapacity, float fillratio)
Here fillratio is 0 or 1.
4. HashSet h = new HashSet(Collection c)
Note
After filling how much ratio new HashSet object will be created , The ratio is called “FillRatio” or “LoadFactor“.
package com.ashok.collections.hashset; import java.util.HashSet; /** * * @author ashok.mariyala * */ public class MyHashSet { public static void main(String args[]) { // HashSet declaration HashSet<string> hset = new HashSet<string>(); // Adding elements to the HashSet hset.add("Ashok"); hset.add("Vinod"); hset.add("Dillesh"); hset.add("Thiru"); hset.add("Naresh"); System.out.println(hset); // Addition of duplicate elements System.out.println(hset.add("Ashok")); System.out.println(hset); // Addition of null values hset.add(null); System.out.println(hset.add(null)); // Displaying HashSet elements System.out.println(hset); } }
Output
[Thiru, Ashok, Dillesh, Vinod, Naresh] false [Thiru, Ashok, Dillesh, Vinod, Naresh] false [null, Thiru, Ashok, Dillesh, Vinod, Naresh]
HashSet Class