Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hashMap doubt

 
adam Lui
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.util.*;
class Dog {
public Dog(String n) { name = n; }
public String name;
public boolean equals(Object o) {
if((o instanceof Dog) &&
(((Dog)o).name == name)) {
return true;
} else {
return false;
}
}
public int hashCode() {return name.length(); }
}

class MapTest {
public static void main(String[] args) {
Map<Object, Object> m = new HashMap<Object, Object>();
Dog d1 = new Dog("clover"); // let's keep this reference
d1.name= "clover";
m.put(d1, "Dog key");
System.out.println(m.get("clover"));
System.out.println(m.get(d1));

}
}



at the second last line, why does it return null?
cant we use an object's value to search an object?

(more confusing, K&B book stated THIS ("clover") would actually WORK)
 
ahmed yehia
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

at the second last line, why does it return null?

Because you dont have an element in the map with the key "clover" so you get null.
Add this to the code and you wont get null:
 
adam Lui
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ahmed Yehia:

Because you dont have an element in the map with the key "clover" so you get null.
Add this to the code and you wont get null:

i have...

d1.name= "clover";
m.put(d1, "Dog key");

this doesnt logically compromise?
 
Gaurav Patrikar
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you do System.out.println(m.get("clover")) it will search for a Key whose value is equal to String object Clover and not d1.

If you try this you will understand what I mean to say.

Dog d2 = new Dog("clover");
d2.name= "clover";
System.out.println(m.get(d2));
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic