我有一个Student
类包含ArrayList
类型Course
,而Course
是类,包含className
,classTime
等字段}等,以及适当的getter和setter。假设我创建了一个ArrayList
课程并将其存储到Student
课程中。
我如何打印特定className
对象的Course
(存储在ArrayList
类中的Student
中)?
到目前为止,我试过这个,下面是类Student
的代码的一部分:
class Student {
ArrayList<Course> studentSchedule;
public ArrayList<Course> getStudentSchedule() {
return studentSchedule;
}
public void setStudentSchedule(ArrayList<Course> studentSchedule) {
this.studentSchedule = studentSchedule;
}
}
然后我有一些代码创建student1
Student
类型的ArrayList
并将Course
className
存入其中。
我想要访问ArrayList
中student1
中第一个对象中的ArrayList<Course> schedule = student1.getStudentSchedule();
System.out.print("\n course name at position 0 is " +
student1.getStudentScheduleClassName(0));
。到目前为止,我有这个,它的工作原理......它没事吗?
Arraylist
为此目的创建另一个schedule
感觉很奇怪......但是我想在第1行中,{{1}}只包含指向该位置的地址,不应该很多空间?
有更合适的方法吗?
答案 0 :(得分:1)
基于上述讨论,我试图完成解决方案供我参考。
import java.util.ArrayList;
import java.util.Iterator;
公共类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";
}
}
}
答案 1 :(得分:0)
将className
转换为Course的实例变量,并在课程中为类名提供getter和setter方法。然后你将打印出班级名称。
答案 2 :(得分:0)
public class Course{
private String className;
public String getClassName(){
return className;
}
public void setClassName(String c){
className =c;
}
}
所以当你拥有这个时,你就可以做到
System.out.println(student1.getStudentSchedule().get(0).getClassName())
答案 3 :(得分:0)
您可以访问第一门课程的班级名称:
System.out.print("\n course name at position 0 is " + schedule.get(0).getClassName());
因为您已经在Course
课程中定义了getter / setter,如上所述。