• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Doubt in HashMap

 
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi ,
This is a example given in K&B book-

Remember that when you use a class that implements Map, any classes that you
use as a part of the keys for that map must override the hashCode() and equals()
methods.


We get null when we try to get the Cat object as Cat class does not implements hashCode and equals.
But just look at the example below-
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 Cat { }
enum Pets {DOG, CAT, HORSE }
class MapTest {
public static void main(String[] args) {
Map<Object, Object> m = new HashMap<Object, Object>();
m.put("k1", new Dog("aiko")); // add some key/value pairs
m.put("k2", Pets.DOG);
m.put(Pets.CAT, "CAT key");
Dog d1 = new Dog("clover"); // let's keep this reference
m.put(d1, "Dog key");
Cat c= new Cat();
m.put(c, "Cat key");
System.out.println(m.get("k1")); // #1
String k2 = "k2";
System.out.println(m.get(k2)); // #2
Pets p = Pets.CAT;
System.out.println(m.get(p)); // #3
System.out.println(m.get(d1)); // #4
System.out.println(m.get(c)); // #5
System.out.println(m.size()); // #6
}
}
Now when we try to add a Cat oject c then we are able to get the answer Cat Key. Does it mean that when we say m.get(new Cat()) we pass a new Cat object as the key not the the same key which we had used to add


m.put(new Cat(), "Cat key");.


Can somebody please explain-when Cat does not implement hashCode() then how are we able to get when we use m.get(c).
Thanks.
 
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Howdy ranchers,

Neha wrote:

Can somebody please explain-when Cat does not implement hashCode() then how are we able to get when we use m.get(c).


implements? Nope.
hashCode() is a method of class Object. You cannot implement it, because it is already there. In every object. You could only override it (what you didn't).


You put a new Cat refered by variable c as a key into the map.
Cat extends Object so hashCode() returns a unique int, so it will be inserted into the map.

You retrieve the value of the key-value pair with the variable c as well when you say:
m.get(c);

When referring the same object, the equals()-method of Object returns true.
Therefore you will get the String "Cat key" back in line #5.



Yours,
Bu.
 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Burkhard,
Can you please explain if a class does not override hashCode() and equals() method then how are we able to get the stuff from the Cat class in the above code.


Remember that when you use a class that implements Map, any classes that you
use as a part of the keys for that map must override the hashCode() and equals()
methods. (Well, you only have to override them if you're interested in retrieving
stuff from your Map. Seriously, it's legal to use a class that doesn't override equals()
and hashCode() as a key in a Map; your code will compile and run, you just won't
find your stuff.)


Another doubt as mentioned earlier why do we get null when we try to add new Cat() as the key and then retrieve by m.get(new Cat()). Is it because we are referring to different objects everytime.
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You should look what the hashCode() and equals() method of class Object do.

Bu.
 
Swati Khanna
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please re-read my quote from K&B book above that 's confusing me.
Thanks
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Howdy,

didn't see, that it was one of your first postings here, so

Welcome to the Ranch!



Back to your question. If you neither override hashCode nor equals you will simply call the methods of class Object.
Because Object returns different hashCodes for every object and returns true in equals() only if the references refer (point to) the same object, you cannot use the HashMap as it should be used.

E.g. if you have two Cat objects that should be meaningfully equal, and you put one into the the map and try to get the key out of it with the other one:


you will get null.


But that is not the way a hashmap should work, you should get a value back with equal objects.
You can get the first Cat back from the map if you get(one), but that is not a way a map should be used. Because then you only can get a value from an object whose references you already have.


Compare the situation above with a tiger version where equals and hashCode are overridden properly:

With the second Tiger that is meaningfully equal to the first, you can get the first back.
Output is now "one", no longer "null". And one.equals(two) is true.


Hope that helped so far.

This one is for the cat:




Yours,
Bu.
[ September 19, 2007: Message edited by: Burkhard Hassel ]
 
Swati Khanna
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot. I got it.
Can you suggest some tutorial on static synchronized methods.
I have few doubts- Can two different instances invoke a static synchronized method at the same time?
 
reply
    Bookmark Topic Watch Topic
  • New Topic