因此,我在arraylist中有几个“学生”对象,每个学生都有一个课程的arraylist。如何访问特定学生的所有课程?提前致谢。

Scanner studentCourse = new Scanner(System.in);
int j = 0;

System.out.println("Which students course(s) do you want to view?");
for(Student l:listStudent) {
    System.out.print(j+1 + ")");
    System.out.println(l);
    j++;
}
int course = studentCourse.nextInt();

int k = s.listCourse.size();//need this to be the size of the correct array list
int l = 0;

while( l < k ){
    System.out.println(s.listCourse.get(0));//need this to print all of the elements in the correct array list
}

break;

public class Student {

    String studentFirstName, studentLastName;
    int studentID;
    double studentGPA;
    ArrayList<Course> listCourse = new ArrayList<>();

}

最佳答案

您的问题非常容易理解,但您的代码却不容易理解。

Student student = studentList.get(indexPosition);
//ArrayList gives this flexibility and that's the advantage of ArrayList over other Lists

if(student.getCoursesList()!=null && !student.getCoursesList().isEmpty()){
    for(Course course: student.getCoursesList()){
        System.out.println(course);
    }
}

关于java - 从存储在arraylist中的对象访问arraylist的所有元素(2维),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22626216/

10-14 11:59
查看更多