File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
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)


boolean b = true;<br />System.out.println ("I believe in Java.<br />Java will make my dream come " + b);
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
 
Similar Threads
Using object as keys in maps
K & B - Generics & Collections
Using HashMap Problem
confusion in HashMaps