Monday, February 15, 2010

java.lang.String.hashCode() doesn't cache 0

public class Main {
   static void test(String s) {
      long start = System.currentTimeMillis();
      for (int N = 1 << 20; N --> 0;) {
         s.hashCode();
      }
      System.out.format("Took %d ms.%n", System.currentTimeMillis() - start);
   }
   public static void main(String[] args) {
      String z = new String(new char[1000]);
      test(z);
      test(z + "!");
   }
}
Run it!
Quiz: what percentage of all Java strings hash to 0?

While looking for a domain name, I found amusing examples of strings that hash to 0.
pollinating sandboxes
schoolworks = perversive
amusement & hemophilias
grinnerslaphappier.org
electrolysissweeteners.net
constitutionalunstableness.net
WRANGLINGMOOCHER.ORG
BLEACHINGFEMININELY.NET
WWW.RACCOONPRUDENTIALS.NET

Update 2/24: stackoverflow.com - Why doesn’t String’s hashCode() cache 0?

No comments:

Post a Comment