Hashcode plays a significant role in adding key value pair in hash based collections like HashMap or LinkedHashMap. In addition the concept of hashcode is also used by HashSet class. The best part of using proper hashcode is that the Big Oh complexity of retrieval operation is O(1).

A poor hashcode algorithm can not only decrease the performance of a hash based collection but also result in unexpected output. Various ways by which hashcode can be generated in a Java application:

Effective Java

Josh Bloch tells the following best practices for overriding the hashcode method in his book “Effective Java”:

Store some constant nonzero value, say 17, in an int variable called result.
Compute an int hashcode c for each field f that defines equals:
If the field is a boolean, compute (f ? 1 : 0)
If the field is a byte, char, short, int, compute (int) f
If the field is a long, compute (int) (f ^ (f >>> 32))
If the field is a float, compute Float.floatToIntBits(f)
If the field is a double, compute Double.doubleToLongBits(f), then hash the resulting long as in above.
If the field is an object reference and this class’s equals method compares the field by recursively invoking equals, recursively invoke hashCode on the field. If the value of the field is null, return 0.
If the field is an array, treat it as if each element is a separate field. If every element in an array field is significant, you can use one of the Arrays.hashCode methods added in release 1.5.
Combine the hashcode c into result as follows: result = 31 * result + c;

Hashcode method in String class:

String class is very famous for its hashcode algorithm as it makes use of all characters from the internal character array. More importance is given to the most significant character and less to least significant character in the character array. The algorithm for generating the hash code in string class looks like as shown below. Note that “s” is the character array used by the string class and “n” is the length of string.

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

Hashcode using Eclipse IDE

Various modern day IDE offer the feature of allowing the generation of hashcode by invoking the right click context menu. A sample hashcode generated by using Eclipse IDE looks like:

	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + a;
		return result;
	}

It is not recommended to use the above code in enterprise level code and better use some third party library like Apache commons for generating the hashcode method in custom classes.

Apache Commons HashcodeBuilder

We can also the Apache Commons hashcode builder for generating the code in our classes. The advantage of using such a third-party library is that tried and tested code from object can be used in our application. The following code shows how to use Apache Commons hash code builder for generating hash code for a custom class:

 public int hashCode(){
        HashCodeBuilder builder = new HashCodeBuilder();
        builder.append(mostSignificantMemberVariable);
	........................
	builder.append(leastSignificantMemberVariable);
        return builder.toHashCode();
    }

As shown in the above code, the most significant member variable should be passed first and then followed by the less significant member variables.

Apache Commons also offers it goes builder for generating equals method for custom classes. The code using the equals builder looks very similar to the above code. In fact the rule about passing the member variables starting from most significant to least significant also applies to the equals builder.

How to generate hashcode method for a class in Java admin Core Java
Hashcode plays a significant role in adding key value pair in hash based collections like HashMap or LinkedHashMap. In addition the concept of hashcode is also used by HashSet class. The best part of using proper hashcode is that the Big Oh complexity of retrieval operation is O(1). A poor...
Hashcode plays a significant role in adding key value pair in hash based collections like HashMap or LinkedHashMap. In addition the concept of hashcode is also used by HashSet class. The best part of using proper hashcode is that the <a href="http://www.javaexperience.com/time-complexity-of-collection-classes/" title="Time complexity of collection classes">Big Oh complexity</a> of retrieval operation is O(1). A poor hashcode algorithm can not only decrease the performance of a hash based collection but also result in unexpected output. Various ways by which hashcode can be generated in a Java application: <h2>Effective Java</h2> Josh Bloch tells the following best practices for <strong>overriding the hashcode method</strong> in his book "Effective Java": <blockquote> Store some constant nonzero value, say 17, in an int variable called result. Compute an int hashcode c for each field f that defines equals: If the field is a boolean, compute (f ? 1 : 0) If the field is a byte, char, short, int, compute (int) f If the field is a long, compute (int) (f ^ (f >>> 32)) If the field is a float, compute Float.floatToIntBits(f) If the field is a double, compute Double.doubleToLongBits(f), then hash the resulting long as in above. If the field is an object reference and this class's equals method compares the field by recursively invoking equals, recursively invoke hashCode on the field. If the value of the field is null, return 0. If the field is an array, treat it as if each element is a separate field. If every element in an array field is significant, you can use one of the Arrays.hashCode methods added in release 1.5. Combine the hashcode c into result as follows: result = 31 * result + c; </blockquote> <h2>Hashcode method in String class:</h2> String class is very famous for its hashcode algorithm as it makes use of <strong>all characters from the internal character array</strong>. More importance is given to the most significant character and less to least significant character in the character array. The algorithm for <strong>generating the hash code</strong> in string class looks like as shown below. Note that "s" is the character array used by the string class and "n" is the length of string. 1 <h2>Hashcode using Eclipse IDE</h2> Various modern day IDE offer the feature of allowing the generation of hashcode by invoking the right click context menu. A sample hashcode generated by using Eclipse IDE looks like: 1 It is not recommended to use the above code in enterprise level code and better use some third party library like Apache commons for generating the hashcode method in custom classes. <h2>Apache Commons HashcodeBuilder</h2> We can also the <strong>Apache Commons hashcode builder</strong> for generating the code in our classes. The advantage of using such a third-party library is that tried and tested code from object can be used in our application. The following code shows how to use Apache Commons hash code builder for generating hash code for a custom class: 1 As shown in the above code, the most significant member variable should be passed first and then followed by the less significant member variables. Apache Commons also offers it goes builder for generating equals method for custom classes. The code using the equals builder looks very similar to the above code. In fact the rule about passing the member variables starting from most significant to least significant also applies to the equals builder.
The following two tabs change content below.
I run this blog with lots of passion. In this website, you will find tutorials on Core Java, Spring, Struts, Web Applications, Portals and Database. Please support me and the website by sharing the posts on your facebook / twitter. You can tap the share button at the top of each post. Thanks for the support.