tags:

views:

42

answers:

2

Hi,

I have this simple class

public class Position{
   int x;
   int y;

   Position(int x,int y){...}

   public int hashCode(){
    Integer ix = this.x;
    Integer iy = this.y;

    return 13*iy.hashCode() + 43*ix.hashCode();
   }
}

Im storing instances in a hashMap, but then cant retrieve them. I fear its the hashcode implementation. Is there any way to implement it when x and y are not Objects?

Thanks in advance

+2  A: 

That you cannot retrieve them has nothing to do with your hashCode implementation.

As Integer#hashCode just returns its value, you could simplify it as

 public int hashCode(){
      return 13*iy+43*ix;
 }

Are you changing ix and iy after putting the object into the map? That is a big no-no and totally screws up the hashtable.

Also, you need to define Position#equals as well.

Thilo
+2  A: 

I have a guess: did you override equals method as well? In Java, when you implement one, you should implement another.

In particular, if you use Position instances as keys, HashMap will compare them with equals. Otherwise, two keys can accidentally have same hash, but different values.

From HashMap#get

if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
            return e.value;
Nikita Rybak
yeap, its there.
Tom
I don't think to override 'equals' method in this case, as Object.equals() is OK for the case:)I agreed with Thilo: It's wrong to change ix and iy after putting the object into the map
卢声远 Shengyuan Lu
+1: That's probably it.
Thilo
@Shenguanl Lu: How is Object.equals() okay?
Thilo
Rule says: if a.equals(b) then a.hashCode()==b.hashCode() is a must. So Object.equals() and Position.hashCode() are complied with it
卢声远 Shengyuan Lu
But as a hash key, you would want to have Position(1,1) being equal to Position(1,1), even if they are different objects.
Thilo
@Thilo: I know your idea, you're right.if equals() isn't overridden, the argument of HashMap.get() needs a identical reference of map key.
卢声远 Shengyuan Lu