DZone
Java Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Java Zone > Hashing Implementation Using java.util.Objects

Hashing Implementation Using java.util.Objects

Implementing your hashing is an ugly, annoying process. Or at least it used to be. A tool introduced in Java 7 has utility methods to make your life easier.

Arun Pandey user avatar by
Arun Pandey
·
Dec. 29, 16 · Java Zone · Tutorial
Like (55)
Save
Tweet
64.65K Views

Join the DZone community and get the full member experience.

Join For Free

Most applications require an extensive hashing implementation, and writing a good hashing algorithm is always a tedious job. To get rid of this ugly and tedious hashCode and equals implementation, Java introduced an API called java.util.Objects in Java 7, which contains a set of utility methods and is useful in combination with Object instances.

Now let's see an example to understand this cool feature.

Here, Person is a class that needs hashCode() and equals() method implementation.

Prior to Java 7

Using Java 6, we generate the equals() and hashCode() methods using the Eclipse IDE.

Person.java

package hashingDemo;

/**
 * @author arun.pandey
 */
public class Person {
  String ssn;
  String name;

  public Person(){}

  public Person(String ssn, String name){
    this.ssn = ssn;
    this.name = name;
  }

  public String getId() {
    return ssn;
  }

  public void setId(String id) {
    this.ssn = id;
  } 

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  /* (non-Javadoc)
 * @see java.lang.Object#hashCode()
 */
  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;

    result = prime * result + ((name == null) ? 0 : name.hashCode());
    result = prime * result + ((ssn == null) ? 0 : ssn.hashCode());
    return result;
  }

  /* (non-Javadoc)
 * @see java.lang.Object#equals(java.lang.Object)
 */
  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;

    if (obj == null)
      return false;

    if (getClass() != obj.getClass())
      return false;

    Person other = (Person) obj;

    if (name == null) {
      if (other.name != null)
        return false;
    } else if (!name.equals(other.name))
      return false;

    if (ssn == null) {
      if (other.ssn != null)
        return false;
    } else if (!ssn.equals(other.ssn))
      return false;

    return true;
  }
}


Java 7 Implementation

Now let's see the same implementation using Java 7 (java.util.Objects) as below.

Person.java

package hashingDemo;

import java.util.Objects;

/**
 * @author arun.pandey
 */
public class Person {
  String ssn;
  String name;

  public Person(){}

  public Person(String ssn, String name){
    this.ssn = ssn;
    this.name = name;
  }

  public String getId() {
    return ssn;
  }
  public void setId(String id) {
    this.ssn = id;
  } 
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }

  @Override
  public int hashCode() {
    return java.util.Objects.hash(getId(), getName());
  }

  @Override
  public boolean equals(Object obj){
    if (obj == this) {
      return true;
    } 

    if (obj instanceof Person) {
      Person other = (Person) obj; 
      return Objects.equals(ssn, other.ssn) && Objects.equals(name, other.name);
    } 
    return false;
  }
}


Test the code to evaluate the above implementation.

HashingTest.java

package hashingDemo;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import junit.framework.Assert;

/**
 * @author arun.pandey
 */
public class HashingTest {
  public static final Log LOG = LogFactory.getLog(HashingTest.class);

  @Test
  public void testHashing() {

    Person person1 = new Person("xxxx123", "Person1");
    Person person2 = new Person("xxxx234", "Person2");

    LOG.info("person1 HashCode ==>> " +person1.hashCode());
    LOG.info("person2 HashCode ==>> " +person2.hashCode());

    Assert.assertFalse(person1.hashCode() == person2.hashCode());
    Assert.assertFalse("Both are same employee...", person1.equals(person2));

    Person person3 = new Person("xxxx567", "Person3");
    Person person4 = new Person("xxxx567", "Person4");

    LOG.info("person3 HashCode ==>> " +person3.hashCode());
    LOG.info("person4 HashCode ==>> " +person4.hashCode());

    Assert.assertEquals(person3.hashCode(), person4.hashCode()); 
    Assert.assertTrue("Both are not same employee...",person3.equals(person4));
  }
}


And test passed as expected. Try it in your next hashing and equals implementation to have better and cleaner code.

I hope this will add a nice feature to your coding. Happy learning!

Implementation

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • 5 Skills SecOps Will Need to Effectively Protect Their Organization Going Forward
  • Setting Up a Dedicated Database Server on Raspberry Pi
  • Understand Source Code — Deep Into the Codebase, Locally and in Production
  • Building a 32-Core Raspberry Pi Cluster From Scratch

Comments

Java Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo