gpt4 book ai didi

java - 访问存储在 ArrayList 中的对象的最佳方式?

转载 作者:行者123 更新时间:2023-12-01 13:16:16 26 4
gpt4 key购买 nike

我有一个 Student 类,其中包含 Course 类型的 ArrayList,并且 Course 是包含一些内容的类像 classNameclassTime 等字段以及适当的 getter 和 setter。假设我创建了一个 Course 的 ArrayList 并将其存储到 Student 类中。

例如,我如何打印特定Course对象的className(该对象存储在存储在中的ArrayList中)学生类)?

到目前为止,我尝试过这个,下面是类 Student 的部分代码:

class Student {
ArrayList<Course> studentSchedule;

public ArrayList<Course> getStudentSchedule() {
return studentSchedule;
}

public void setStudentSchedule(ArrayList<Course> studentSchedule) {
this.studentSchedule = studentSchedule;
}
}

然后我有一些代码创建了 Student 类型的 student1 并将 CourseArrayList 存储到其中.

假设我想访问 student1ArrayList 的第一个对象中的 className。到目前为止我已经有了这个并且它可以工作......可以吗?

ArrayList<Course> schedule = student1.getStudentSchedule();

System.out.print("\n course name at position 0 is " +
student1.getStudentScheduleClassName(0));

为此目的创建另一个 Arraylist 感觉很奇怪......但后来我想,从第 1 行开始,schedule 将只包含指向位置并且不应该占用太多空间?

有更合适的方法吗?

最佳答案

根据上述讨论我尝试完成解决方案供我引用。

导入java.util.ArrayList;

导入java.util.Iterator;

公共(public)类ListExample {

public static void main(String[] args) {

Student student1 = new Student();

ArrayList<Course> student1Schedule = new ArrayList<Course>();
student1Schedule.add(new Course("Computer Science", "Training Room"));
student1Schedule.add(new Course("Mobile App Development", "Training Room 2"));

student1.setStudentSchedule(student1Schedule);
// Prints only one course
System.out.println(" ** Course" + student1.getStudentSchedule().get(0).toString());
// Print all the courses attended by the student
ArrayList<Course> studentDetails = student1.getStudentSchedule();
Iterator<Course> studentIterator = studentDetails.iterator();
while (studentIterator.hasNext()) {
Course courseName = studentIterator.next();
System.out.println(courseName);
}

}


static class Student {

private ArrayList<Course> studentSchedule;

public ArrayList<Course> getStudentSchedule() {
return studentSchedule;
}

public void setStudentSchedule(ArrayList<Course> studentSchedule) {
this.studentSchedule = studentSchedule;
}
}

static class Course {

private String courseName;
private String className;

public Course (String courseName, String className){
this.className =className;
this.courseName = courseName;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}

public String toString (){
return "Course Name :" + this.courseName + "\n" + "Class Name : " + className + "\n";

}

}

}

关于java - 访问存储在 ArrayList 中的对象的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22442056/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com