public class Person{
private String name;
public Person(String name){this.name=name;}
public boolean equals(Person p){
return p.name.equals(this.name)
}
}A.the equals method does not properly override the object.equals method;
B.complilation fails because the private attribute p.name cannot be accessed in line 5;
C.to work correctly with hash-base date structures,this class must also implement the hashcode method;
D.when adding person object to java.util.set collection,the equals method in line 4 will prevent duplicates.

解决方案 »

  1.   

    That method in class Object take another Object as parameter.
      

  2.   

    This method simply overload that method in class Object, instead of override it.
    The correct way to override it is as follows.public boolean equals(Object o) {
        return (o instanceof Person) && ((Person)o).name.equals(this.name);
    }
      

  3.   

    我同一z_lping(Schemer)的说法,他说的很好!
      

  4.   

    yes,it's just a overloard in the question.
    override requires the same parameters
      

  5.   

    请教一下(o instanceof Person) && ((Person)o)的作用是什么呢?
      

  6.   

    o 是 Person或其子类的对象将o转型为Person, 然后调用它的equals方法...
      

  7.   

    如果单纯为了“将o转型为Person, 然后调用它的equals方法...”,只用((Person)o)不行吗;为什么还要&&(o instanceof Person)?
      

  8.   

    如果你的o不是Person类型,强制类型转换是要报错滴!
      

  9.   

    the function's parameter is Object......
    so the answer is A
      

  10.   

    boolean equals(Object o){
       if(this == o) return true;
       if(o == null) return false;
       if(!this.getClass().getName().equals(o.getClass().getName())) return false;
       Person p = (Person)o;
       if(this.name.equals(p.name)) return true;
       else return false;
    }
      

  11.   

    1:建议楼主看看effective java,很好的一本书。里面就有提到为什么是选择A.对于Oject对象的equals()方法,如果其参数不是Object类型,那么这个equals()方法叫做重载(overload),而不是重写(override)。2:重写equals()方法时,必须满足基本的三个条件:对称、传递、自反。否则重写的equals()方法肯定是错误的。3:楼上有兄弟说不必加上o instanceof Person,这个说法不合理,如果给Person一个子类SubPerson,那么Person.equals(SubPerson)返回true, 而SubPerson.equals(Person)返回false,这显然违反了对称性。
      

  12.   

    CoreJava(6th Ed) P159页,这样解释的:
    Java语言规范要求equals方法满足以下特点:
    1、自反性,2、对称性,3、传递性,4、一致性,5、对任意非空引用x,x.equals(null)应当返回false
    上面的语句应该违反了对称性,如果x.equals(y),y.equals(x)也应该是成立的,但是如果上面的person p是person的子类对象,则equals返回就不是true了,所以重载不正确……
      

  13.   

    我模糊的明白了A的意思,是不是说这个equals方法不是重写超类的equals方法,里面的参数应该是Object,应该是这意思吧.
      

  14.   

    不是,A的意思是说没有正确的重载equals方法
      

  15.   

    boolean equals(Object o){
       if(this == o) return true;
       if(o == null) return false;
       if(!this.getClass().getName().equals(o.getClass().getName())) return false;
       Person p = (Person)o;
       if(this.name.equals(p.name)) return true;
       else return false;
    }
      if(!this.getClass().getName().equals(o.getClass().getName())) return false;
    --------------------------
    这句难道没问题吗?