在Driver类中调用Linked List类方法

时间:2013-11-06 10:11:23

标签: java class object methods linked-list

我有一个名为MyCollege(Driver)的类和一个名为LinkedList的类。我有在LinkedList中创建的方法,但我不确定如何调用它们。我希望能够按照排序顺序或按输入顺序将对象输入到链接列表中,具体取决于用户选择的内容。

2 个答案:

答案 0 :(得分:0)

默认情况下List实现按插入顺序维护元素。对于你想要插入顺序的地方你很好。但是,如果您需要不同的订单,则必须使用其他集合(例如TreeSet)或在添加元素后对List进行排序。

如果元素为Comparable,并且您希望它们按此顺序排序,则可以使用TreeSet(如果您没有任何重复项)或使用Collections.sort(list)。如果您需要不同的订单,则需要实施Comparator。然后,您可以将其传递给TreeSet构造函数或Collections.sort

答案 1 :(得分:0)

使用新的int变量存储用户的订单首选项:

int order;

现在将for循环更改为:

    for(int i = 0; i < 10; i++)
    {
    //ask to input details
    System.out.println("-------------------------------------------------");
    System.out.println("Please input the information below:");
    System.out.println("-------------------------------------------------");
    System.out.println("Please input the student's name : ");
    name = scan.nextLine();
    System.out.println("Please input the student's number : ");
    number = scan.nextLine();
    System.out.println("Please input the student's course code : ");
    courseCode = scan.nextLine();
    System.out.println("Please input the student's course entry year : ");
    entryYear = scan.nextInt();
    scan.nextLine();

    System.out.println("Please input the order you want to put Student in the List
    [1 for Sorted and any other number to add at the end of this list ] : ");
    order = scan.nextInt();

    s1 = new Student(name, number, courseCode, entryYear); //create new student

    if(order == 1){
    list.sorted(s1);
    } else {
    list.add(s1); //add s1 to list
    }
}

编辑

您可以定义Comparator按学生编号对列表中的元素进行排序:

class Student {
...
private static final Comparator<Student> STU_COMP = new Comparator<Student>() {
    @Override
    public int compare(Student s1, Student s2) {
        return s1.getStudentNo().compareTo(s2.getStudentNo());
    }
};
...
}

现在您可以使用Collections.sort使用此比较器对列表进行排序:

Collections.sort(list, STU_COMP); 
相关问题