我需要搜索對象集合並找到哪個對象包含與我讀入的字符串匹配的'name'變量。下面是每個Student對象的樣子:使用.equals()來比較兩個對象的變量
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()
方法,但我找不到使其工作的方法。
請確保您的代碼編譯。你不能使用「class」作爲參數名稱 – kritzikratzi 2013-03-04 23:44:32
請粘貼完整的函數'loadStudentProjects'。另外爲什麼你在Employee類中的'Student'有'.equals'?錯字? – Ankit 2013-03-04 23:45:06