HashSet
HashSet
Key points:
- HashSet is an Implementation class of Set Interface.
- It implements 2 marker Interfaces i.e. Serializable and Cloneable.
- The underlined data structure of HashSet is HashTable.
- The default capacity of HashSet is 16, and it grows based on load factor or fill ratio.
- Internally it gets the HashCode number of e1 and keeps it as a key in the table.
- It doesn't allow duplicate elements based on the Hashcode.
Constructors of HashCode
No-argument constructor:
- HashSet s1=new HashSet();
- Creates an empty HashSet with a capacity of 16 and a default load factor is 0.75.
Two-argument constructor:
- HashSet s1=new HashSet(n,f);
- Users can provide initial capacity and load factors based on their requirements.
- n--> int type specifies initial capacity.
- f--> float type specifies load factor.
Collection-type argument:
- HashSet s1=new HashSet(c1);
- Let's c1 is the collection with n elements.
- Creates a HashSet with the elements of specified elements and with a default load factor of 0.75.
Example to store unique records of Students. Students having duplicate IDs should not be allowed.
package quipoin;
public class Student {
int id;
String name;
double marks;
public Student(int id, String name, double marks) {
this.id = id;
this.name = name;
this.marks = marks;
}
@Override
public int hashCode() {
return id;
}
@Override
public boolean equals(Object obj) {
return this.hashCode() == obj.hashCode();
}
@Override
public String toString() {
return "Strudent[ Id=" + id + ",Name=" + name + ",Marks=" + marks + "+]";
}
}
package quipoin;
import java.util.HashSet;
import java.util.Iterator;
public class SetDemo1 {
public static void main(String[] args) {
HashSet<Student> s1 = new HashSet<>();
s1.add(new Student(101, "Ramu", 65.50));
s1.add(new Student(103, "Akash", 69.70));
s1.add(new Student(109, "Vivek", 75.50));
s1.add(new Student(107, "Rakesh", 45.20));
s1.add(new Student(103, "Bharath", 80.00));
// to avoid duplicates we need to override hashCode()
Iterator<Student> i1 = s1.iterator();
System.out.println("-----------------------");
System.out.println("Id\tName\tMarks");
System.out.println("-----------------------");
while (i1.hasNext()) {
Student student = (Student) i1.next();
System.out.println(student.id + "\t" + student.name + "\t" + student.marks);
}
}
}
Output:
--------------------
Id Name Marks
--------------------
101 Ramu 65.5
103 Akash 69.7
107 Rakesh 45.2
109 Vivek 75.5
- In the above example in the Student class, we have overridden the hashcode method based on the Student Id
- The equals method will compare based on the ID and return a Boolean result.
- We can observe the SetDemo1 class we added five students but in the result only four records are visible. Because the ID of the two students is the same, so one duplicate element(object) is eliminated.