The ultimate superclass, Part 2

1 2 Page 2
Page 2 of 2

Listing 3. Correcting hash-based collection difficulty by also overriding hashCode()

import java.util.HashMap;
import java.util.Map;

final class Employee
{
   private String name;
   private int age;

   Employee(String name, int age)
   {
      this.name = name;
      this.age = age;
   }

   @Override
   public boolean equals(Object o)
   {
      if (!(o instanceof Employee))
         return false;

      Employee e = (Employee) o;
      return e.getName().equals(name) && e.getAge() == age;
   }

   String getName()
   {
      return name;
   }

   int getAge()
   {
      return age;
   }

   @Override
   public int hashCode()
   {
      int result = 31;
      result = 37*result+name.hashCode();
      result = 37*result+age;
      return result;
   }
}

public class HashDemo
{
   public static void main(String[] args)
   {
      Map<Employee, String> map = new HashMap<>();
      Employee emp = new Employee("John Doe", 29);
      map.put(emp, "first employee");
      System.out.println(map.get(emp));
      System.out.println(map.get(new Employee("John Doe", 29)));
   }
}

Listing 3's Employee class declares a pair of fields on which an overall hash code must be obtained. The overriding hashCode() method first initializes result to 31, then merges the String-based name field's hash code into this variable, and finally merges the int-based age field into this variable, which is subsequently returned.

Compile Listing 3 (javac HashDemo.java) and run this application (java HashDemo). You should observe the following output:

first employee
first employee

What's next?

In Part 3, I wrap up this series by exploring toString() along with the wait/notification methods. I also discuss Object's methods in the context of interfaces and Java 8.

download
Get the source code for this post's applications. Created by Jeff Friesen for JavaWorld

The following software was used to develop the post's code:

  • 64-bit JDK 7u6

The post's code was tested on the following platform(s):

  • JVM on 64-bit Windows 7 SP1
1 2 Page 2
Page 2 of 2