我的问题涉及在ArrayList中的对象中搜索特定变量并返回变量。其中一个问题是Student对象包含多个变量字段。
我试图在对象中找到一个特定的变量,然后从数组列表中返回它。
这是主要方法:
Student s1 = new Student ("student1", 123, "MIS");
Student s2 = new Student("student2", 231, "Finance");
Student s3 = new Student ("student3", 432, "MIS");
Student s4 = new Student ("student4", 438, "Marketing");
Student s5 = new Student ("student5", 429, "MIS");
Student s6 = new Student ("student6", 215, "Accounting");
Student s7 = new Student ("student7", 287, "MIS");
Student s8 = new Student ("student8", 401, "MIS");
ArrayList<Student> myList = new ArrayList<Student>();
myList.add(s1);
myList.add(s2);
myList.add(s3);
myList.add(s4);
myList.add(s5);
myList.add(s6);
myList.add(s7);
myList.add(s8);
StudentDatabaseImplementation st = new StudentDatabaseImplementation();
st.setTheListOfStudents(myList);
st.printTheListOfStudents(myList);
st.getStudent(429);
System.out.println("The name of the student : "+
st.getStudent(429).getName());
在我创建的Student课程中,我写道:
public class Student{
private String name;
private int CWID, ID;
private String major, maj;
private ArrayList<Student> myList = new ArrayList<Student>()
public Student(String name, int CWID, String major)
{this.name=name;CWID=ID; String Major = maj;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public ArrayList<Student> getAllStudents() {return myList;}
-->public Student getStudent(int CWID){if(myList.contains CWID)
{getName();}}
public void setTheListOfStudents(ArrayList<Student> myList) {
this.myList = myList;}
public String getMajorName() {return majorName;}
public void setMajorName(String majorName) {this.majorName = majorName;}
public int getCWID() {return CWID;}
public void setCWID(int studentId) {this.studentCWID = studentCWID;}
private String majorName;
private int studentCWID;
我还能做些什么来返回用户名吗?
答案 0 :(得分:0)
虽然您的代码似乎没问题,但您可以覆盖toString()
类的Student
方法,并使其返回用户的名称。
public class Student {
@Override
public String toString() {
return getName();
}
}
然后你可以打电话
System.out.println("The name of the student : "+
st.getStudent(429));
答案 1 :(得分:0)
这是您应该如何实现getStudent
方法。它返回null,如果找不到student,或者CWID等于CWID参数的学生,如果在列表中至少有Student具有该CWID。
public Student getStudent(int CWID){
return myList.stream().filter(s -> s.getCWID()==CWID).findAny().orElse(null);
}
我建议您评估地图以存储学生。
Map<int,Student>
其中键是CWID。通过这种方式,你不应该迭代找到学生。