使用HashMap实现HashSet是否存在问题? [英] Are there problems of implementing HashSet using HashMap?

查看:120
本文介绍了使用HashMap实现HashSet是否存在问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,HashSet是使用HashMap实现的。因此,当我们添加一个项目到集合中时,下面的代码被执行。

  public boolean add(E e){
返回map.put(e,PRESENT)== null;

$ / code>

当两个不同但具有相同哈希的对象被添加到HashSet的;它会(HashSet)包含对象或发生什么呢?

以及 .hash()。两件事情是不一样的,除非 .equals()返回true。所以如果两个对象不同但具有相同的散列,它们都将被存储,并且都是可用的,因为 .equals()仍然会返回 false



在内部,散列用于决定存储对象的位置,但仍然可以存储具有相同散列的多个对象(因为它变得更加复杂,所以性能会受到一些损失)。


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 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).

这篇关于使用HashMap实现HashSet是否存在问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆