In java HashSet is implemented using a HashMap. So when we add an item to the set the following code is executed.
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
what happens when two objects that are different but having equal hash is added to the HashSet; will it (HashSet) contain both the objects or what happens then?
hashmap uses
.equals()as well as.hash(). two things are not the same unless.equals()returns true. the same will be true of hashset.so if two objects are distinct but have the same hash, they will both be stored, and both available, because
.equals()will still returnfalse.it’s true that, internally, the hash is used to decide where to store the objects, but multiple objects with the same hash can still be stored (there’s a slight performance penalty because it gets more complicated, but that’s all).