我正在尝试在一系列测试后填充ArrayList。它工作正常,但有点太精细了。它将每个值添加到数组列表两次。这是我的代码,我不明白问题从哪里来,因为我只有fullresult.add一次?
public ArrayList<Student> filterClasses (String classe){
ArrayList<Student> fullresult = new ArrayList<Student>();
for (int i = 0; i < studentDB.StudentList.size(); i++) {
int classesSize = studentDB.StudentList.get(i).classes().size()/3;
for (int j = 0; j < classesSize ; j++){
if (studentDB.StudentList.get(i).classes().contains(classe)){
fullresult.add(studentDB.StudentList.get(i));
}
}
}
System.out.println(fullresult);
return fullresult;
}
解
我不需要第二个for循环:
public ArrayList<Student> filterClasses (String classe){
ArrayList<Student> fullresult = new ArrayList<Student>();
for (int i = 0; i < studentDB.StudentList.size(); i++) {
if (studentDB.StudentList.get(i).classes().contains(classe)){
fullresult.add(studentDB.StudentList.get(i));
}
}
System.out.println(fullresult.toString());
return fullresult;
}
答案 0 :(得分:2)
我真的不明白你为什么这么做
int classesSize = studentDB.StudentList.get(i).classes().size()/3;
所以这里的代码可以完成我认为你想要的东西:
public ArrayList<Student> filterClasses (String classe){
ArrayList<Student> fullresult = new ArrayList<Student>();
for (Student student : studentDB ) {
if (student.classes().contains(classe)){
fullresult.add(student);
}
}
}
System.out.println(fullresult);
return fullresult;
}