首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Java中重写equals方法

如何在Java中重写equals方法
EN

Stack Overflow用户
提问于 2011-11-18 17:41:39
回答 10查看 284.9K关注 0票数 124

我正在尝试覆盖Java中的equals方法。我有一节课People它基本上有2个数据字段nameage。现在我想覆盖equals方法,这样我就可以在两个People对象之间进行检查。

我的代码如下

public boolean equals(People other){
    boolean result;
    if((other == null) || (getClass() != other.getClass())){
        result = false;
    } // end if
    else{
        People otherPeople = (People)other;
        result = name.equals(other.name) &&  age.equals(other.age);
    } // end else

    return result;
} // end equals

但当我写下age.equals(other.age)它给了我错误,因为equals方法只能比较字符串和年龄是整数。

解决方案

我用过==运算符,我的问题就解决了。

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8180430

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档