我注意到在Java 6的String源代码中,hashCode只缓存0以外的值.下面的代码片段展示了性能上的差异:
public class Main{
static void test(String s) {
long start = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
s.hashCode();
}
System.out.format("Took %d ms.%n", System.currentTimeMillis() - start);
}
public static void main(String[] args) {
String z = "Allocator redistricts; strict allocator redistricts strictly.";
test(z);
test(z.toUpperCase());
}
}
Run Code Online (Sandbox Code Playgroud)
在ideone.com中运行此命令将提供以下输出:
Took 1470 ms.
Took 58 ms.
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:
为了您的娱乐,这里的每一行都是一个散列为0的字符串:
pollinating sandboxes
amusement & hemophilias
schoolworks = perversive
electrolysissweeteners.net
constitutionalunstableness.net
grinnerslaphappier.org
BLEACHINGFEMININELY.NET
WWW.BUMRACEGOERS.ORG
WWW.RACCOONPRUDENTIALS.NET …Run Code Online (Sandbox Code Playgroud) 鉴于这种:
String s1= new String("abc");
String s2= new String("abc");
String s3 ="abc";
System.out.println(s1==s3);
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
System.out.println(s3.hashCode());
Run Code Online (Sandbox Code Playgroud)
输出是:
false
false
true
true
96354
96354
96354
Run Code Online (Sandbox Code Playgroud)
这里==给每个对象赋予false,但每个String对象的哈希码是相同的.为什么会这样?