The following prototype function mimics the hashCode() function of java.lang.String in Java:


String.prototype.hashCode = function() {
  for(var ret = 0, i = 0, len = this.length; i < len; i++) {
    ret = (31 * ret + this.charCodeAt(i)) << 0;
  }
  return ret;
};

Depending on the version of Java that you are running, what is returned from this function may not be the same thing that is returned in Java. On the other hand, this implementation is computationally equivalent to the algorithm shown on this Java doc page. As you may notice, due to the limit on an int in Java, I imposed the same limit on the size of the number returned by this function. The number returned will always be in the -2^31 to 2^31-1 range.

Here are some example JavaScript calls:


alert("H".hashCode()); // 72
alert("Chris West".hashCode());  // -438087208
alert("Hello world!!!".hashCode());  // 638403293
alert("This is a Java string".hashCode());  // 586653468

Try using the hashCode() function on the above strings in Java and see if the returned values match. They did for me:


public class test{
  public static void main(String args[]) {
    System.out.println("If true 4 times, everything is good:");
    System.out.println("H".hashCode() == 72);
    System.out.println("Chris West".hashCode() == -438087208);
    System.out.println("Hello world!!!".hashCode() == 638403293);
    System.out.println("This is a Java string".hashCode() == 586653468);
  }
}

2 Comments

Chris West's Blog » JavaScript Snippet – String.prototype.hashCode() | Neorack Tutorials · October 12, 2011 at 1:55 AM

[…] is the original post: Chris West's Blog » JavaScript Snippet – String.prototype.hashCode() Posted in JAVA | Tagged following-prototype, function-mimics, hashcode, JAVA, leave, […]

Chris West's Blog » JavaScript Snippet – String.prototype.hashCode() · October 12, 2011 at 5:12 AM

[…] Chris West's Blog » JavaScript Snippet – String.prototype.hashCode() Tags: public class test, java lang, Chris West, main string […]

Leave a Reply

Your email address will not be published. Required fields are marked *