【问题标题】:Check if two objects have the same attributes检查两个对象是否具有相同的属性
【发布时间】:2018-02-03 15:02:13
【问题描述】:

您好,我想比较两个对象是否具有相同的属性 我创建了 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));
    }
}

【问题讨论】:

标签: java object attributes boolean


【解决方案1】:

因为您使用的是默认的equals() 方法,而不是您创建的egal() 方法。如果您致电 egal(),您会看到所需的输出。

或者不是创建一个新的egal() 方法,而是覆盖类中现有的equal 方法。

【讨论】:

  • 为了让编译器帮助你解决像你这样的小错别字,你可以将@Override附加到你的egal() / equals()方法定义中,告诉编译器这个方法不是新发明的,而是为了为其他地方定义的东西定义特定于类的行为。
猜你喜欢
  • 1970-01-01
  • 2012-12-31
  • 1970-01-01
  • 2021-08-19
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 2015-01-25
相关资源
最近更新 更多