• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

hashMap doubt

 
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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)
 
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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));
reply
    Bookmark Topic Watch Topic
  • New Topic