Understanding the workings of equals and hashCode in a HashMap

Posted by andandandand on Stack Overflow See other posts from Stack Overflow or by andandandand
Published on 2009-12-12T19:00:10Z Indexed on 2014/08/23 10:21 UTC
Read the original article Hit count: 310

Filed under:
|
|
|

I have this test code:

import java.util.*;

class MapEQ {

  public static void main(String[] args) {
   Map<ToDos, String> m = new HashMap<ToDos, String>();
   ToDos t1 = new ToDos("Monday");
   ToDos t2 = new ToDos("Monday");
   ToDos t3 = new ToDos("Tuesday");
   m.put(t1, "doLaundry");
   m.put(t2, "payBills");
   m.put(t3, "cleanAttic");
   System.out.println(m.size());
} }

class ToDos{

  String day;

  ToDos(String d) { day = d; }

  public boolean equals(Object o) {
      return ((ToDos)o).day == this.day;
 }

// public int hashCode() { return 9; }
}

When // public int hashCode() { return 9; } is uncommented m.size() returns 2, when it's left commented it returns three. Why?

© Stack Overflow or respective owner

Related posts about java

Related posts about hashmap