我用Java編寫一個程序,我有以下問題:有沒有辦法通過它的名字獲得一個ArrayList元素?
//this is the important part of my class student
public class Student{
private String name;
public Student(String name){
this.name = name;
}
//Getter
public String getName() {
return name;
}
}
//this is the other class (could be the main for example)
public class Load {
private ArrayList<Student> student= new ArrayList<Student>();
student.add(new Student(name));
}
在節目後來我又需要那些學生。我可以這樣得到他們:
System.out.println(student.get(0));
但我沒有學生人數。有沒有一種方法可以通過班級學生的姓名來獲取他們?
迭代通過列表,檢查是否student.getName()等於您的搜索並返回,如果有的話。由於名稱不一定是唯一的,你可能想要返回一個列表 –
你可以檢查列表中是否存在名字student.contains(「dfighter3」) – VedX
'student.stream()。filter(x - > x.equals 「name」))。findAny()。orElse(null)' – px06