• Post Reply Bookmark Topic Watch Topic
  • New Topic

Get value in map by key is object class  RSS feed

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am reading "Item 9: Always override hashCode when you override equals" in Effective Java book.
I creat entity Person:



class Main have:



My problem that can't get object so I put into map before.

Could anybody help me to solve.
Thanks!
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

I don't see the problem. You are using getClass() rather than instanceof which can cause problems if you make subclasses of Person. I presume your class is immutable, otherwise it is an error to have a hash code as a field.
If you have setXXX methods, then your class is mutable and you must delete the field hashCode and calculate the hash code anew every time the hashCode method is called.You are now failing to maintain the general contract for hashCode. The result of equals() has changed but the hash codes haven't changed.

I tried your code with slight changes and got a real result from
System.out.printf("p.hashCode = 0x%h, map.get(p) = %s%n", p, map.get(p));
p.hashCode = 0x5edcc57, map.get(p) = ifi
You are simply not doing anything with the value returned in line 6.

I suggest this for your hash code method:-Let the hash method do the hard work
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!