簡體   English   中英

檢查兩個對象是否具有相同的屬性

[英]Check if two objects have the same attributes

您好,我想比較兩個對象是否具有我創建的John和John2相同的屬性,將John與John 2比較時為假,而將John與John本人比較為真,這是為什么呢?

public class Test {

    public static void main(String[] args) {
        Student John = new Student("John", 15);
        Student John2 = new Student("John", 15);

        System.out.println(John.equals(John2)); // FALSE why ?
        System.out.println(John.equals(John)); // TRUE 
    }

}

public class Student {

    String name;
    int age;

    public Student(String name, int age) {

        this.name = name;
        this.age = age;
    }

    public boolean egal(Student c) {

        return ((this.name).equals(c.name) && (this.age) == (c.age));
    }
}

因為您使用的是默認的equals()方法,而不是創建的egal() 如果調用egal()則會看到所需的輸出。

或者,也可以使用類中現有的equal方法代替創建新的egal()方法。

暫無
暫無

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

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