【发布时间】:2014-10-10 14:49:47
【问题描述】:
这可能不是真实世界的场景,只是想知道会发生什么,下面是代码。
我正在创建一组 UsingSet 类的对象。
根据Java中的哈希概念,当我第一次添加包含“a”的对象时,它会创建一个哈希码为97的桶并将对象放入其中。
再次,当它遇到一个带有“a”的对象时,它会调用类 UsingSet 中重写的 hashcode 方法,它会得到 hashcode 97 那么接下来是什么?
由于我没有重写 equals 方法,默认实现将返回 false。那么值“a”的对象将保存在哪个桶中,与之前的哈希码为 97 的对象保存在同一个桶中?还是会创建新的存储桶? 有人知道它将如何在内部存储吗?
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
class UsingSet {
String value;
public UsingSet(String value){
this.value = value;
}
public String toString() {
return value;
}
public int hashCode() {
int hash = value.hashCode();
System.out.println("hashcode called" + hash);
return hash;
}
public static void main(String args[]) {
java.util.Set s = new java.util.HashSet();
s.add(new UsingSet("A"));
s.add(new UsingSet("b"));
s.add(new UsingSet("a"));
s.add(new UsingSet("b"));
s.add(new UsingSet("a"));
s.add(new Integer(1));
s.add(new Integer(1));
System.out.println("s = " + s);
}
}
输出是:
hashcode called65
hashcode called98
hashcode called97
hashcode called98
hashcode called97
s = [1, b, b, A, a, a]
【问题讨论】:
-
在内部,
HashMap用于存储HashSet的值。此外,HashMap下还有一个方法hash(),它应用补充散列函数来防御不良散列码。 -
应该是同一个bucket,可以在调试器中签入。
-
ans = [A, a, a, 1, b, b]
标签: java collections set