This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes hashMap doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "hashMap doubt" Watch "hashMap doubt" New topic
Author

hashMap doubt

adam Lui
Ranch Hand

Joined: Sep 03, 2007
Posts: 186
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

Joined: Apr 22, 2006
Posts: 424

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

Joined: Sep 03, 2007
Posts: 186
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

Joined: Jan 10, 2007
Posts: 5
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));
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: hashMap doubt