为什么我的 equals 方法不能识别对象变量?

Why does my equals method not recognize object variables?

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

以下是我目前的资料。

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() 方法比较学生姓名和部分吗?

您缺少将对象类型转换为学生 class;

Student std = (Student)y;
@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

嗯..我不确定,但我认为 Eclipse 也应该有这个功能 - 'add standard equals method' - 使用它然后你的 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.
}