相关疑难解决方法(0)

为什么String的hashCode()没有缓存0?

我注意到在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)

所以我的问题是:

  • 为什么String的hashCode()没有缓存0?
  • Java字符串哈希值为0的概率是多少?
  • 对于散列为0的字符串,每次重新计算哈希值的性能损失的最佳方法是什么?
  • 这是缓存值的最佳实践方式吗?(即缓存除一个以外的所有?)

为了您的娱乐,这里的每一行都是一个散列为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)

java string hashcode

75
推荐指数
6
解决办法
1万
查看次数

java中==,equals和hashcode的示例

鉴于这种:

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对象的哈希码是相同的.为什么会这样?

java equals hashcode

5
推荐指数
2
解决办法
7295
查看次数

标签 统计

hashcode ×2

java ×2

equals ×1

string ×1