开发者

Java hashCode of a POD?

开发者 https://www.devze.com 2023-01-12 10:51 出处:网络
I have this simple class public class Position{ int x; int y; Position(int x,int y){...} public int hashCode(){

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 can't retriev开发者_如何学Ce them. I fear its the hashcode implementation. Is there any way to implement it when x and y are not Objects?


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.


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消