Java Life Rap Song

This is a pretty funny and yet kinda good rap song about Java (the programming language of course :)):

[hide-this-part morelink=”Show the Video”]

[/hide-this-part]

JavaScript Snippet – String.prototype.hashCode()

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);
  }
}