问题
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?
回答1:
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 return false
.
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).
回答2:
Yes, a hashmap will contain both elements. I can't find the specific method that it uses, but popular methods of dealing with collisions include using a linked list for each bucket, or just sticking elements in nearby empty buckets.
来源:https://stackoverflow.com/questions/11680751/are-there-problems-of-implementing-hashset-using-hashmap