| Author |
A Question about Java Maps
|
Bob Sherry
Greenhorn
Joined: Jun 27, 2008
Posts: 20
|
|
The following Java code is based upon a question from the testing softare that came with the book "Sun Certified Programmer for Java 5" by K Sierra and B Bates. However, I have modified the code. Here is my version of the 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 { public boolean equals( Object o1 ) { System.out.println( "equals called: "); if ( !(o1 instanceof ToDos) ) return false; ToDos dos1 = (ToDos)o1; if ( task.equals( dos1.task ) ) return true; return false; } public int compareTo( ToDos dos1 ) { System.out.println( "compareTo called: "); System.out.println( task ); System.out.println( dos1.task ); System.out.println( task.compareTo( dos1.task ) ); return task.compareTo( dos1.task ); } String task; ToDos(String t) { task = t; }; } The first change was to fix the syntax error. This code now compiles. However, it prints out 3 for the size of the map. I would like it to print out 2. That is, I want the code to consider t1 and t2 to be the same object since they have the same value for the key. How do I do this? Thanks Bob
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16695
|
|
You forgot to override the hashCode() method. In order to use an object as a key to a hashmap, you need to comform to the equals() - hashCode() contract. Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Bob Sherry
Greenhorn
Joined: Jun 27, 2008
Posts: 20
|
|
Thanks for the response. I added the following code to the class ToDos: public int hash( ToDos o1 ) { System.out.println( "hash called" ); return 0; } However, the string hash called did not appear in the output. I also tried making the argument of type Object. That did not work either. The output is still 3. Any other ideas? Thanks Bob
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16695
|
|
It would help if you named the method correctly. The method is named hashCode(). Henry
|
 |
Bob Sherry
Greenhorn
Joined: Jun 27, 2008
Posts: 20
|
|
Henry, Thanks for the response. I changed the name to hashCode and that still did not work. Any other ideas? Bob
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16695
|
|
No offense, but you are not trying very hard. A quick google would have told you that the signature is also incorrect. Henry
|
 |
 |
|
|
subject: A Question about Java Maps
|
|
|