Are there problems of implementing HashSet using HashMap?

本小妞迷上赌 提交于 2019-12-13 05:54:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!