1

继我的这个问题之后:制作这个 Java 程序的最佳方法是什么?

建议我在 Lecturer 类和 Course 类中存储一个列表。所以我做到了,它看起来像这样:

public class Lecturer
{
    private String id;  
    private String name;  
    List<Course> courses = new ArrayList<Course>();  // a list to hold the courses


    public Lecturer(String idIn, String nameIn)     // arguments of the constructor
    {
        id = idIn;
        name = nameIn;

    }

}

除了有讲师列表之外,课程课程也是如此。但我不明白的是,在那里放置一个列表究竟有什么作用?因为我不知道在哪里放置 ArrayList 的方法,例如从中添加和删除讲师?

有人可以解释这样做的目的吗?

我使用另一种方法,该方法基本上是将数组列表及其方法放在讲师和课程的两个单独的类中,然后我只需将其作为属性添加到课程和讲师类中,例如:

public class Lecturer
{
    private String id;  
    private String name;  
    private CourseList courses;  // COurseList is the class with the arraylist and methods


    public Lecturer(String idIn, String nameIn)     // arguments of the constructor
    {
        id = idIn;
        name = nameIn;
        courses = new CourseList();
    }

}

我希望我是有道理的,因为过去两周我一直坚持一件事,这似乎没有人能理解。

谢谢

4

2 回答 2

1

使用第一种方法,您需要公开允许客户端代码向这些列表添加内容的方法。所以,你可以有:

public class Lecturer
{
    List<Course> courses = new ArrayList<Course>();  // a list to hold the courses

    public Lecturer(String idIn, String nameIn)
    {
        /* do stuff */
    }

    public void addCourse(Course newCourse)
    {
        this.courses.add(newCourse);
    }
}

您可以为 Course 课程做类似的事情。完成这些设置后,您可以执行以下操作:

public static void main(String[] args)
{
    Lecturer bob = new Lecturer(1, "Bob Smith");
    Course math = new Course("Math 101");

    // wire them together such that Bob teaches Math 101
    bob.addCourse(math);
    math.addLecturer(bob);
}

我认为这可以解决您的问题,但是这种双向循环关系有时是设计不佳的标志。不过,只有你知道你真正的任务是什么,所以我希望这会有所帮助!

于 2009-04-20T19:20:40.537 回答
0

正如有人在上一个问题中回答的那样,我建议使用Map<Lecturer, List<Course>>,这意味着“Map不同讲师 ( ) 之间的关联 ( )Lecturer与他们教授的课程列表( ) 之间的关联 ( ) List<Course>,您可以将其实例化为 new HashMap<Lecturer, List<Course>>。否则,存储每个列表,您将复制功能。

一旦您声明了Courses c1, c2, ..., cnaLecturer l教授,您将它们关联到Map mas m.put(l, c)where cis aList课程中,声明为new LinkedList<Course>(),并添加为c.add(c1); c.add(c2); ... c.add(cn);

如果我清楚地解释自己。

您可以阅读http://java.sun.com/docs/books/tutorial/collections/interfaces/map.htmlhttp://java.sun.com/docs/books/tutorial/collections/implementations/map.html有关使用Maps 的更多帮助。

要获得反向关联,您可以轻松使用以下代码:

Collection<Course> courses = m.values();
Map<Course, List<Lecturer>> reverseAssociation = new HashMap<Course, List<Lecturer>>;

    for (Course course : courses) {
        List<Lecturer> lecturersTeachingCourse = new LinkedList<Lecturer>();

        for (Lecturer lecturer : m.keySet()) {
            if (lecturer.teaches(course)) {
                lecturersTeachingCourse.add(lecturer);
            }
        }

        coursesTaught.put(course, lecturersTeachingCourse);
    }

其中,只要Lecturer.teaches(Course)查询讲师是否教授通过的课程,设置reverseAssociation为课程-讲师关联。(当然,您应该将该代码封装为 Lecturers 中的方法)。

祝JavaNoob好运!我们都去过一次!

于 2009-04-20T19:16:16.723 回答