-1

我需要搜索对象集合并找到哪个对象包含与我读入的字符串匹配的“名称”变量。下面是每个学生对象的样子:

public Student(String name, String class)
{
    this.name = name;
    this.class = class;
}

我还在.equals()员工类中写了这个方法来做我的对象比较。

public boolean equals(Student student)
{
    return this.name.equals(student.name); 
}

在我的主要课程中,我将学生的姓名转换为一个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++;

即使我知道第一次比较应该显示名称匹配,此代码也会为每次比较返回 false。有人告诉我,我需要将要比较的字符串名称转换为对象并使用.equals()方法,但我找不到让它工作的方法。

4

2 回答 2

10

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

public boolean equals(Object o) {
    ...
}

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

  1. 检查这o确实是一个Student实例。
  2. 假设1为真,检查othis获得名称。

所以你可以尝试一些类似的东西

(o instanceof Student) && name.equals(((Student) o).name)
于 2013-03-04T23:45:07.093 回答
0

而不是equals我建议您使用compareTo(或compareToIgnoreCase):

public int compareTo(Student s) {
    return this.name.compareTo(s.name);
}

compareTo0 如果字符串相等,则返回一个与0任何其他情况不同的数字。

要与Student对象进行比较,您可以使用以下内容:

public void aMethod(ArrayList students) {
    Student aStudent;
    int count;
    count = 0;

    aStudent = newStudent("name", "class") // Construct the Student object with the appropriate parameters
    for (Student s : students) {
        if s.compareTo(aStudent) == 0 {
            // Do something
        }
    }
}

希望这可以帮助你

于 2013-03-04T23:50:30.820 回答