tangsilian 2016-03-06 11:31 采纳率: 100%
浏览 1476
已采纳

关系多态的问题,为何重写了equals 却没有调用

import java.util.*;

class Name{
private String firstname,secondname;
public Name(String firstname,String secondname){
this.firstname=firstname;
this.secondname=secondname;

}
public String getFirstName(){return firstname;}
public String getsecondName(){ return secondname; }
public String toString(){ return firstname+" "+secondname;}

public boolean equals(Object obj) {
if(obj instanceof Name){

return true;
} return super.equals(obj);
}

public int hashcode(){
return firstname.hashCode();

}
}

public class TestCollection {

public static void main(String[] args) {
    Collection c=new HashSet();
    c.add("hello");
    c.add(new Name("uzi","omg"));
    c.add(new Integer(100));
    c.remove("hello");      
    c.remove(new Integer(100));
    System.out.println(c.remove(new Name("uzi","omg")));    
    System.out.println(c);
}

}
程序结果如下//
false
[uzi omg]

重写了Name 中的equals()结果依然没变 为何没有调用Name里的equals??

  • 写回答

4条回答 默认 最新

  • 毕小宝 博客专家认证 2016-03-06 13:23
    关注

    之所以你的remove操作失败,是因为你重新的equals和hashCode不妥当,因为java约定equals和hashCode方法,要求equals返回true时,也一定要有相同的hashCode。
    你要重写equals的话,应该用Eclipse自动生成的方法,保证这一规则成立。
    删除这两个方法,重新用Eclipse的右键-》source-》generate equals() and hashCode()。选择需要用的属性,这样就能remove返回true了。
    这篇文章写的很详细你可以参考下:http://www.importnew.com/16517.html

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮