【问题标题】:Why does my equals method not recognize object variables?为什么我的 equals 方法不能识别对象变量?
【发布时间】:2016-01-25 09:40:44
【问题描述】:

我只是想编写一个比较学生姓名和部分的 equals 方法。如果名称和部分相同,则 equals 方法应该打印 true。否则它应该打印错误。

以下是我目前所拥有的。

public class Student {

    private String name;
    private int section;

    public Student(String name, int section) {
        this.name = name;
        this.section = section;
    }

    public boolean equals(Object y) {

        if (this.name.equals(y.name) && this.section.equals(y.section)) {
            return true;    
        }
        else {
            return false;
        }
    }
}

错误在于y.namey.section。 Eclipse 告诉我 namesection 无法解析为字段。

我的问题是,谁能告诉我如何修复我的代码,以便我可以使用 .equals() 方法比较学生姓名和部分?

【问题讨论】:

  • 看起来您正在尝试“装箱”和“拆箱”无论 y 是什么。在你的情况下,y 可能真的是一个学生。
  • 与问题无关(问题已被@Thilo解决),但if(condition){return true;}else{return false;}可以替换为return condition;

标签: java equals


【解决方案1】:
@Override  // you should add that annotation
public boolean equals(Object y) {

您的y 是任意Object,不一定是Student

你需要有类似的代码

if (y == this) return true;
if (y == null) return false;
if (y instanceof Student){
  Student s = (Student) y;
  // now you can access s.name and friends

【讨论】:

  • 试图将答案放在新问题的 FIRST 之下是一场真正的斗争。我放弃了。
  • @Blauhirn 你不需要成为第一个。 Jon Skeet 经常是最后一个回答 :)
  • @Blauhim 好。重要的是要正确,而不是首先。真理不是时间的函数。
  • @Pshemo 我知道。只是指这样的问题,其中解决方案相当明显。没有冒犯。
  • 没有必要使用instanceof 检查null,因为instanceoffalse 生成null
【解决方案2】:

嗯..我不确定,但我认为 Eclipse 也应该使用这个功能 - '添加标准 equals 方法' - 使用它,然后你的 IDE 生成绝对正确的 equals 方法......但它是关于编码速度优化。现在让我们谈谈equals方法。通常equals 方法合约在其自身上定义transitiveness...所以如果a 等于b 那么b 等于a。在这种情况下,建议有严格的限制:

public boolean equals(Object x) {
  if (x == this) {
    return true; // here we just fast go-out on same object
  }
  if (x == null || ~x.getClass().equals(this.getClass())) {
    return false; // in some cases here check `instanceof`
                  // but as I marked above - we should have
                  // much strict restriction
                  // in other ways we can fail on transitiveness
                  // with sub classes
  }
  Student student = (Student)y;
  return Objects.equals(name, student.name)
         && Objects.equals(section, student.section);
  //please note Objects - is new (java 8 API)
  //in order of old API usage you should check fields equality manaully.
}

【讨论】:

    【解决方案3】:

    您缺少将对象类型转换为 Student 类;

    Student std = (Student)y;
    

    【讨论】:

    • 你不应该无条件这样做
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 2019-07-02
    • 2017-10-11
    相关资源
    最近更新 更多