Wednesday, January 1, 2014

How to override hashcode in Java example - Tutorial

Equals and hashcode methods are two primary but yet one of most important methods for java developers to be aware of. Java intends to provide equals and hashcode for every class to test the equality and to provide a hash or digest based on content of class. Importance of hashcode increases when we use the object in different collection classes which works on hashing principle e.g. hashtable and hashmap. A well written hashcode method can improve performance drastically by distributing objects uniformly and avoiding collision. In this article we will see how to correctly override hashcode() method in java with a simple example. We will also examine important aspect of hashcode contracts in java. This is in continuation of my earlier post on overriding equals method in Java, if you haven’t read already I would suggest go through it.

General Contracts for hashCode() in Java

1) If two objects are equal by equals() method then there hashcode returned by hashCode() method must be same.

2) Whenever hashCode() mehtod is invoked on the same object more than once within single execution of application, hashCode() must return same integer provided no information or fields used in equals and hashcode is modified. This integer is not required to be same during multiple execution of application though.

3) If two objects are not equals by equals() method it is not require that there hashcode must be different. Though it’s always good practice to return different hashCode for unequal object. Different hashCode for distinct object can improve performance of hashmap or hashtable by reducing collision.

To better understand concept of equals and hashcode and what happens if you don’t override them properly I would recommend understanding of How HashMap works in Java

Overriding hashCode method in Java

Override java hashcode exampleWe will follow step by step approach for overriding hashCode method. This will enable us to understand the concept and process better.

1) Take a prime hash e.g. 5, 7, 17 or 31 (prime number as hash, results in distinct hashcode for distinct object)
2) Take another prime as multiplier different than hash is good.
3) Compute hashcode for each member and add them into final hash. Repeat this for all members which participated in equals.
4) Return hash

  Here is an example of hashCode() method

    public int hashCode() {
        int hash = 5;
        hash = 89  hash + ( != null ? : 0);
        hash = 89  hash + (int) ( ^ ( >>> 32));
        hash = 89  hash + this.age;
        return hash;

It’s always good to check null before calling hashCode() method on members or fields to avoid NullPointerException, if member is null than return zero. Different data types has different way to compute hashCode.Integer members are simplest we just add there value into hash, for other numeric data-type are converted into int and then added into hash. Joshua bloach has full tables on this. I mostly relied on IDE for this.

Better way to override equals and hashCode

hashcode in Java exampleIn my opinion better way to override both equals and hashcode method should be left to IDE. I have seen Netbeans and Eclipse and found that both has excellent support of generating code for equals and hashcode and there implementations seems to follow all best practice and requirement e.g. null check , instanceof check etc and also frees you to remember how to compute hashcode for different data-types.

Let’s see how we can override hashcode method in Netbeans and Eclipse.

In Netbeans
1) Write your Class.
2) Right click + insert code + Generate equals() and hashCode().

How to override java hashcode
In Eclipse
1) Write your Class.
2) Go to Source Menu + Generate hashCode() and equals()

Things to remember while overriding hashcode in Java

1. Whenever you override equals method, hashcode should be overridden to be in compliant of equals hashcode contract.
2. hashCode() is declared in Object class andreturn type of hashcode method is int and not long.
3. For immutable object you can cache the hashcode once generated for improved performance.
4. Test your hashcode method for equals hashcode compliance.
5. If you don't override hashCode() method properly your Object may not function correctly on hash based collection e.g. HashMap, Hashtable or HashSet.

Complete example of equals and hashCode

public class Stock {
       private String symbol;
       private String exchange;
       private long lotSize;
       private int tickSize;
       private boolean isRestricted;
       private Date settlementDate;
       private BigDecimal price;
       public int hashCode() {
              final int prime = 31;
              int result = 1;
              result = prime * result
                           + ((exchange == null) ? 0 : exchange.hashCode());
              result = prime * result + (isRestricted ? 1231 : 1237);
              result = prime * result + (int) (lotSize ^ (lotSize >>> 32));
              result = prime * result + ((price == null) ? 0 : price.hashCode());
              result = prime * result
                           + ((settlementDate == null) ? 0 : settlementDate.hashCode());
              result = prime * result + ((symbol == null) ? 0 : symbol.hashCode());
              result = prime * result + tickSize;
              return result;
       public boolean equals(Object obj) {
              if (this == obj) return true;
              if (obj == null || this.getClass() != obj.getClass()){
                     return false;
              Stock other = (Stock) obj;
this.tickSize == other.tickSize && this.lotSize == other.lotSize && 
this.isRestricted == other.isRestricted &&
(this.symbol == other.symbol|| (this.symbol != null && this.symbol.equals(other.symbol)))&& 
( ==|| ( != null && &&
(this.settlementDate == other.settlementDate|| (this.settlementDate != null &&this.settlementDate.equals(other.settlementDate))) &&
(this.price == other.price|| (this.price != null && this.price.equals(other.price)));


Writing equals and hashcode using Apache Commons EqualsBuilder and HashCodeBuilder

EqualsBuilder and HashCodeBuilder from Apache commons are much better way to override equals and hashcode method, at least much better than ugly equals, hashcode generated by Eclipse. I have written same example by using HashCodebuilder and EqualsBuilder and now you can see how clear and concise they are.

    public boolean equals(Object obj){
        if (obj instanceof Stock) {
            Stock other = (Stock) obj;
            EqualsBuilder builder = new EqualsBuilder();
            builder.append(this.symbol, other.symbol);
            builder.append(this.lotSize, other.lotSize);
            builder.append(this.tickSize, other.tickSize);
            builder.append(this.isRestricted, other.isRestricted);
            builder.append(this.settlementDate, other.settlementDate);
            builder.append(this.price, other.price);
            return builder.isEquals();
        return false;
    public int hashCode(){
        HashCodeBuilder builder = new HashCodeBuilder();
        return builder.toHashCode();
    public static void main(String args[]){
        Stock sony = new Stock("6758.T", "Tkyo Stock Exchange", 1000, 10, false, new Date(), BigDecimal.valueOf(2200));
        Stock sony2 = new Stock("6758.T", "Tokyo Stock Exchange", 1000, 10, false, new Date(), BigDecimal.valueOf(2200));

        System.out.println("Equals result: " + sony.equals(sony2));
        System.out.println("HashCode result: " + (sony.hashCode()== sony2.hashCode()));

Only thing to concern is that it adds dependency on apache commons jar, most people use it but if you are not using than you need to include it for writing equals and hashcode method.

Related Java tutorials


oakleyses said...

louis vuitton handbags, oakley sunglasses, louboutin, longchamp outlet, nike shoes, louis vuitton outlet stores, chanel handbags, burberry outlet, prada outlet, jordan shoes, tiffany and co, michael kors outlet, tory burch outlet, louis vuitton outlet, longchamp handbags, nike free, true religion jeans, michael kors outlet, kate spade outlet, polo ralph lauren outlet, tiffany and co, prada handbags, polo ralph lauren outlet, michael kors outlet, michael kors outlet, longchamp handbags, oakley sunglasses, ray ban sunglasses, kate spade handbags, burberry outlet, louis vuitton outlet, louboutin outlet, louboutin, coach factory outlet, air max, air max, coach outlet, gucci outlet, christian louboutin shoes, michael kors outlet, coach purses, ray ban sunglasses, michael kors outlet, louis vuitton, coach outlet store online, true religion jeans, oakley sunglasses cheap

oakleyses said...

ralph lauren, lululemon, air max, hollister, north face, nike air max, polo lacoste, vanessa bruno, timberland, vans pas cher, louboutin, louis vuitton, oakley pas cher, air max pas cher, nike roshe run, air max, true religion outlet, barbour, sac longchamp, air force, hollister, sac louis vuitton, nike free, polo ralph lauren, nike trainers, louis vuitton uk, nike roshe, sac hermes, longchamp, michael kors, sac burberry, sac guess, mulberry, new balance pas cher, converse pas cher, sac louis vuitton, hogan outlet, nike tn, north face, true religion outlet, ray ban pas cher, michael kors, air jordan, nike blazer, nike free pas cher, michael kors pas cher, abercrombie and fitch, ray ban sunglasses

oakleyses said...

mac cosmetics, mont blanc, marc jacobs, canada goose outlet, nike huarache, vans shoes, soccer jerseys, hollister, giuseppe zanotti, beats by dre, abercrombie and fitch, longchamp, insanity workout, celine handbags, bottega veneta, ghd, nfl jerseys, north face outlet, chi flat iron, ugg boots, birkin bag, ugg australia, canada goose, herve leger, ugg pas cher, rolex watches, valentino shoes, canada goose uk, canada goose, ferragamo shoes, canada goose, ugg boots, uggs outlet, north face jackets, soccer shoes, asics running shoes, new balance shoes, p90x, lululemon outlet, canada goose jackets, mcm handbags, instyler, babyliss pro, ugg, wedding dresses, jimmy choo outlet, reebok outlet, nike roshe run

oakleyses said...

parajumpers, karen millen, air max, converse, pandora charms, moncler, louboutin, moncler, links of london, lancel, juicy couture outlet, oakley, hollister, pandora charms, supra shoes, thomas sabo, canada goose, gucci, wedding dresses, timberland boots, swarovski crystal, air max, coach outlet store online, moncler, ray ban, canada goose, moncler, ugg, louis vuitton, swarovski, hollister, montre homme, moncler, hollister clothing store, ralph lauren, rolex watches, moncler outlet, moncler, iphone 6 cases, baseball bats, juicy couture outlet, toms shoes, vans, pandora jewelry, ugg, converse shoes

Anna said...

Great and Useful Article.

Online Java Training

Online Java Course

Java EE course

Java Course in Chennai

Java Training in Chennai

Java Training Institutes in Chennai

Java Interview Questions

Java Interview Questions