【发布时间】:2019-11-28 01:28:18
【问题描述】:
我有一个名为会话的抽象类。讲座和教程延长了会议。然后我有一个名为注册的课程,其中包含课程列表(讲座和教程)。如何在 Enrollment 中遍历会话列表并仅从会话列表中返回 Lectures 列表?
我的下一个问题是我是否应该存储 2 个列表。一个讲座列表和一个教程列表,而不是 1 个会话列表?这是因为会话列表对我来说毫无用处,我每次都必须遍历它以获取有关讲座和教程的信息。有没有办法让我得到所有的讲座对象?我是java新手。
public class Enrolment {
private List<Session> sessions;
public Enrolment() {
this.sessions = new ArrayList<>();
}
public addSession(Session session) {
this.sessions.add(session);
}
}
public class Session {
private int time;
public Session(int time) {
this.time = time;
}
}
public class Lecture extends Session {
private String lecturer;
public Lecture(int time, String lecturer) {
super(time);
this.lecturer = lecturer;
}
}
public class Tutorial extends Session {
private String tutor;
private int tutorScore;
public Tutorial(int time, String tutor, int tutorScore) {
super(time);
this.tutor = tutor;
this.tutorScore = tutorScore;
}
}
public class test {
public static void main(String[] args) {
Enrolment newEnrolment = new Enrolment();
Lecture morningLec = new Lecture(900, "Dr. Mike");
newEnrolment.addSession(morningLec);
Tutorial afternoonTut = new Tutorial(1400, "John Smith", 3);
newEnrolment.addSession(afternoonTut);
Lecture middayLec = new Lecture(1200, "Mr. Micheals");
newEnrolment.addSession(middayLec);
Tutorial NightTut = new Tutorial(1900, "Harry Pauls", 4);
newEnrolment.addSession(NightTut);
}
}
【问题讨论】:
-
我应该存储 2 个列表。一份讲座清单和一份教程清单...:也许问题应该是:你真的需要
Session类本身吗? -
@ernest_k 讲课对象和教程对象都有时间。而
Session基本上是不重复时间的东西(拥有一个抽象类是有意义的)。 -
在所有实例中,复制并非总是不好。有时这是一个很好的权衡。如果所有
Session抽象增加的是您现在面临的复杂性,那么也许应该质疑它。 -
我同意 ernesk_k。有充分的理由拥有一个抽象类并不意味着你会在每个地方都使用它,即使你不想要这个抽象。您不会创建
Object的列表,因为您可以这样做,但因为您需要。您的Session列表也是如此。
标签: java list loops class arraylist