This is one of the tricky interview questions. Interviewer asked when a duplicate object is inserted into HashSet will it
a. Replace the old value with new one (or)
b. The new item is not inserted
Answer to the above question
Item isn't inserted to the HashSet. As per the Java documentation 'public boolean add(E e)' method, adds the specified element to this set if it is not already present. If this set already contains the element, the call leaves the set unchanged and returns false.
Let’s experiment with an example.
HashSetDuplicateValue.java
package com.sample.app.collections;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class HashSetDuplicateValue {
private static class Employee {
private int id;
private String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
return id == other.id;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + "]";
}
}
public static void main(String args[]) {
Set<Employee> empSet = new HashSet<>();
System.out.println("Adding emp1 with id 1");
Employee emp1 = new Employee(1, "Krishna");
empSet.add(emp1);
System.out.println(empSet);
System.out.println("\nAdding emp2 with id 1");
Employee emp2 = new Employee(1, "Ram");
empSet.add(emp2);
System.out.println(empSet);
}
}
Output
Adding emp1 with id 1 [Employee [id=1, name=Krishna]] Adding emp2 with id 1 [Employee [id=1, name=Krishna]]
In the above snippet,
a. I defined Employee class where id is used as hash code. So two employee objects are equal when their id’s are same.
b. I defined two employee objects emp1 and emp2 with same id.
c. When I inserted both emp1 and emp2 to HashSet, emp2 is not inserted since as per the hashCode and equals contract employee with id 1 is already present in HashSet.
Reference
https://docs.oracle.com/javase/8/docs/api/java/util/HashSet.html
https://self-learning-java-tutorial.blogspot.com/2015/12/how-hashmap-works-in-java.html
You may like
Understanding ConcurrentModificationException in Java
No comments:
Post a Comment