June 12, 2011

Java Collections Framework: Map Example with HashMap and equals() and hashCode() implementation

The HashMap implementation of the Map interface uses hashing to store and find objects. Putting a good implementation of the hashCode() method optimizes searching for objects.

The containsKey() and the containsValue() methods use the equals() method to check for meaningful equality of objects. Classes that have not implemented the equals() methods will not be checked for meaningful equality and will only be checked for referential equality by the containsKey() and the containsValue() methods.


package info.icontraining.collections;

import java.util.*;

public class HashMapExample {

   public static void main(String[] args) {
      Map<Customer, Integer> map = new HashMap<Customer, Integer>();

      map.put(new Customer("Dinesh", "Atlanta"), 1);
      map.put(new Customer("Tanvi", "Norcross"), 2);
      map.put(new Customer("Laksh", "Duluth"), 3);
      map.put(new Customer("Dinesh", "Alpharetta"), 4);

      System.out.println("Size of Map = " + map.size());  
      System.out.println(map.containsKey(new Customer("Laksh", "Duluth")));       }


package info.icontraining.collections;
public class Customer {

   private String customerName;
   private String customerCity;
   public Customer(String customerName, String customerCity) {
      this.customerName = customerName;
      this.customerCity = customerCity;
   public String getCustomerName() {
      return this.customerName;
   public String getCustomerCity() {
      return this.customerCity;
   public int hashCode() {
      return customerName.length() + customerCity.length();
   public boolean equals(Object c) {
      if ((this.customerName.equals(((Customer)c).customerName)) 
          && (this.customerCity.equals(((Customer)c).customerCity))) {
         return true;
      return false;

No comments:

Post a Comment