最近和朋友讨论时,突然朋友抛出一段代码。如下:
Map<Set,Integer> map = new HashMap<>();
Set s1 = new HashSet();
s1.add(1);
s1.add(2);
Set s2 = new HashSet();
s2.add(1);
s2.add(2);
map.put(s1,1);
map.put(s2,2);
System.out.println(map.size());
当时第一个感觉就是输出是 2 。
不过很遗憾,如果是这样,就不会被记录了,输出结果如下:
1
很显然这里和想象中的不一样。
开始,我认为,HashSet 对象作为 HashMap 的 key,并没有什么问题。这里有两个 HashSet 对象,所以,作为 key 应该也是两个 key ,最后的结果应该也是两个。在自己的印象中,就算是对象作为 key 不同的对象,也应该是不同的。
但是结果并不是如此,所以我第一感觉就是应该确认,map.put() 方法是否将两个HashSet 作为一个key了 ?
put 方法中判断 重复是根据 key 的对象的 hashCode 来判断的。
HashMap 里面计算哈希值的函数如下:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
那么看一下HashSet 的 hashCode 的函数,就可以。
一般 hashCode 函数是由 Object对象提供的。
public native int hashCode();
如果有不同,那就是 HashSet 重写了 hashCode 函数。
HashSet 本身没有实现 这个函数,但是 HashSet 继承于 AbstractSet ,在 AbstractSet 里面有实现。
public int hashCode() {
int h = 0;
Iterator<E> i = iterator();
while (i.hasNext()) {
E obj = i.next();
if (obj != null)
h += obj.hashCode();
}
return h;
}
这里是累加 HashSet 对象里面的 HashCode 值。
那么如果是放入的 Integer 对象,它的哈希值是怎么计算的呢?
public int hashCode() {
return Integer.hashCode(value);
}
直接使用的是 Integer 的值。
综上所述,HashSet 对象 在这里例子里面,s1 和 s2 的哈希值是一样的。
可以使用代码修改一下
Map<Set,Integer> map = new HashMap<>();
Set s1 = new HashSet();
s1.add(1);
s1.add(2);
Set s2 = new HashSet();
// 这里改成 2
s2.add(2);
s2.add(2);
map.put(s1,1);
map.put(s2,2);
System.out.println(map.size());
这样输出的结果就是 2 了。