[英]Searching and adding to array list
what i'm trying to do with the method below is look for a specific student in an array list that where the name and unique number(HUN) match the key and keyInt respectively. 我想用下面的方法做的是在一个数组列表中寻找一个特定的学生,该数组的名称和唯一编号(HUN)分别与key和keyInt相匹配。 Once that student is found it should add to the local array list returnStudent and return it.
找到该学生后,应将其添加到本地数组列表中returnStudent并将其返回。 However the line
returnStudent.add(student(i));
但是该行
returnStudent.add(student(i));
is giving me an error and i can't figure out how to fix it,i need it to add the specific student to the local array list. 给我一个错误,我不知道如何解决它,我需要它来将特定的学生添加到本地数组列表中。
public ArrayList<Student1> searchByKey(String key, int keyInt)
{
ArrayList<Student1> returnStudent = new ArrayList<Student1>();
Student1 student = new Student1(key);
int i = 0;
while(i <= students.size())
{
if(student.getName().equals(key) && student.getHUN() == keyInt)
{
return Student.add(student(i));
}
i=i+1;
}
return returnStudent;
}
Thanks in advance. 提前致谢。
Change 更改
returnStudent.add(student(i));
to 至
returnStudent.add(student); // student is the element
to add to a specific index, use - 要添加到特定索引,请使用-
returnStudent.add(i, student); // i is the index to add element at
Note - since you have initialized i=0
you shall iterate through i < students.size()
or you might end up accessing get(i)
on the list for the value that doesn't exist (base indexed to 0). 注意 -由于已初始化
i=0
,因此应迭代i < students.size()
否则最终可能会访问列表中的get(i)
以get(i)
不存在的值(基索引为0)。
The other way to do what you are trying to achieve is using Java8 as - 完成您要实现的目标的另一种方法是将Java8用作-
ArrayList<Student1> students = new ArrayList<>();
public ArrayList<Student1> searchByKey(String key, int keyInt) {
ArrayList<Student1> returnStudent = new ArrayList<>();
Student1 student = new Student1(key);
students.forEach(element -> {
if (element.getName().equals(key) && element.getHUN() == keyInt) {
returnStudent.add(element);
}
});
return returnStudent;
}
You loop through students
. 你遍历
students
。 But add student(i)
. 但是添加
student(i)
。 Note the s at the end. 请注意末尾的。 Change the add to
students(i)
. 将添加项更改为
students(i)
。
Assuming students
is an ArrayList
with prepopulated data, you can do the following. 假设
students
是一个包含预填充数据的ArrayList
,则可以执行以下操作。
public ArrayList<Student1> searchByKey(String key, int keyInt) {
ArrayList<Student1> returnStudent = new ArrayList<Student1>();
for(Student1 student1 : students) {
if(student1.getName().equals(key) && student1.getHUN() == keyInt) {
returnStudent.add(student1);
}
}
return returnStudent;
}
I have changed the while loop to foreach loop to make it look simpler and easily understandable. 我将while循环更改为foreach循环,以使其看起来更简单易懂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.