【发布时间】:2017-07-03 22:47:43
【问题描述】:
我用Java写了一个程序,遇到以下问题:
//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() 是否等于您的搜索,如果是则返回。由于名称不一定是唯一的,您可能希望返回 List
-
你可以检查名字是否出现在列表中,student.contains("dfighter3")
-
student.stream().filter(x -> x.equals("name")).findAny().orElse(null) -
为什么不使用
Map<String, Student>(或者更好的是GuavaMultimap<String, Student>来支持多个同名学生)? -
我的名字是独一无二的