java如何在学生对象的数组列表中找到ID
public class Student { //student object class containing name and id
String name;
int ID;
public Student(String name, int ID) {
this.name = name;
this.ID = ID;
}
@Override
public String toString() {
return name +" "+ ID;
}
}
//another class with two array lists, an array of students in a class and an array of students waiting for help
ArrayList<Student> inClass = new ArrayList<Student>();
ArrayList<Integer> inLine = new ArrayList<Integer>(); //IDs of students who are waiting for help
public boolean addStudentInLine(Integer id) {
for(int i = 0; i<inClass.size(); i++) {
if (inClass.get(i).ID != id) {
return false;
}
if (inClass.get(i).ID == id) {
inClass.add(id);
}
}
}
对于addStudentInLine方法,如果id存在于inClass Arraylist中,我需要将id添加到integer Arraylist inLine中。(只有班级中的学生才能获得帮助)如果该id在inClass arrayList中不存在,请返回false。我不知道如何遍历inClass arrayList以查看id是否已经存在,因为inClass arrayList由学生对象组成。我试过了。contain()方法,但它似乎也不起作用。有人能帮忙吗
# 1 楼答案
您应该在
addStudentInLine
方法中反转条件,如果任何Student
id与ID
匹配,则将ID
添加到inLine
列表并返回true
,否则只返回'false'也可以使用
for-each
块