日期:2014-05-20  浏览次数:20798 次

java.util.Set.contains的问题!
我写了一个类,并复写了equals方法,


                                      Position           p   =   new   Position(5,   5);;
      Position           p1   =   new   Position(7,   6);;
执行    
            p.equals(p1);
          返回true;
但是         Set <Position>   set   =   new   HashSet <Position> ();
                        set.add(p1);
                        set.contains(p);//返回false!!!!!!!why????!!
                   
查了jdk文档
/////////////////////
boolean   contains(Object   o)

        如果   set   包含指定的元素,则返回   true。更确切地讲,当且仅当   set   包含满足   (o==null   ?   e==null   :   o.equals(e))   的元素   e   时返回   true。
    ////////////////////

我已经复写了equals了!为什么根本就没有执行我复写的方法呀?


public   class   Position   {
int   x,   y;
@Override
public   boolean   equals(Object   obj)   {
//   TODO   Auto-generated   method   stub
if   (obj   ==   null)
return   false;
System.out.println( "I 'm   in   equals!!!!!!!!!! ");
boolean   re   =   obj.getClass().equals(this.getClass());
if   (re)   {
Position   p   =   (Position)   obj;
if   ((p.x   !=   this.x)   ||   (p.y   !=   this.y))
re   =   false;
}

return   re;
}

Position(int   x,   int   y)   throws   OutException   {
if   (x   <   0   ||   y   <   0   ||   x   >   7   ||   y   >   7)   {
throw   new   OutException();
}   else   {
this.x   =   x;
this.y   =   y;
}

}
}

------解决方案--------------------
你还要重写 hashCode 方法,这个是 Eclipse 自动生成的。

@Override
public int hashCode() {
  final int PRIME = 31;
  int result = 1;
  result = PRIME * result + x;
  result = PRIME * result + y;
  return result;
}
------解决方案--------------------
重写了 equals方法,也要重写一下
public int hashCode()方法。
HashSet的contains返回true,当且仅当equals返回true并且hashCode返回相等的值。

另外,楼上说的问题是不是笔误?

------解决方案--------------------
感觉这个hashCode用 6 * x + y 就行了.保证没重复,而且均匀分布
不过6这个系数和你的点的取值范围有关.
------解决方案--------------------
判断对象是否相等是根据hashCode是否相等来的。不是写了equals方法就足够