使用.equals()来比较两个对象的变量

Dex*_*ter -1 java equals object

我需要搜索一个对象集合,找到哪个对象包含一个与我读入的字符串匹配的'name'变量.下面是每个Student对象的样子:

public Student(String name, String class)
{
    this.name = name;
    this.class = class;
}
Run Code Online (Sandbox Code Playgroud)

我还在.equals()employee类中编写了这个方法来进行对象比较.

public boolean equals(Student student)
{
    return this.name.equals(student.name); 
}
Run Code Online (Sandbox Code Playgroud)

在我的主课程中,我将学生的名字转换为一个Student对象,并使用该.equals()方法与其他每个学生进行比较.

public static void loadStudentProjects(ArrayList students)
Student currentStudent;
String studentName = "name";

  while (count < students.size())
  {
    currentStudent = Students.create(studentName); 
 //The Student object is initialized as (name, null)

System.out.println(currentStudent.equals(students.get(count)));
count++;
Run Code Online (Sandbox Code Playgroud)

即使我知道第一个比较应该显示名称匹配,但此代码对每个比较都返回false.我被告知我需要转换我正在与一个对象进行比较的String名称并使用一个.equals()方法,但是我找不到一种方法来使它工作.

ars*_*jii 10

您正在重载 equals方法,而不是覆盖它.看起来应该更像

public boolean equals(Object o) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

在你的情况下,要检查任意对象o是否等于this学生,你想要

  1. 检查那o确实是一个Student实例.
  2. 假设1为真,检查othis具有名称.

所以你可以尝试一些方法

(o instanceof Student) && name.equals(((Student) o).name)
Run Code Online (Sandbox Code Playgroud)

  • 这是_always_使用`@Override`注释的一个重要原因. (7认同)