簡體   English   中英

為什么我的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()方法比較學生的姓名和部分嗎?

@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也應該使用此功能-“添加標准的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.
}

您缺少將強制對象轉換為學生類的內容;

Student std = (Student)y;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM