Home » tools

hashCode() in Java 1.5

2 September 2006 2,059 Views No Comment

Can anybody think of a reason why you can’t just have a generic hashCode() utility in Java 1.5 that utilizes autoboxing and variable argument lists? I’ve been using the following code:

public static int computeHashCode(Object... o) {  int result = 17;  for (int i = 0; i < o.length; i++) {   result = 37 * result + (null == o[i] ? 0 : o[i].hashCode());  }  return result;}

It could be called as follows:

public int hashCode() {   return computeHashCode(var1, var2, var3, var4, var5);}

Because of autoboxing, it supports primitives and it seems like it would be easier and faster to use that the Jakarta Commons’ HashCodeBuilder.

Technorati Tags: ,

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.