使用比较器比较Java中的对象属性

时间:2017-05-08 18:10:27

标签: java comparable

我正在处理我的DS / A作业,我不能为我的生活弄清楚如何使用Comparable / Comparator接口将我的Object的特定属性标记为比较和排序的关键。我们正在使用已经提供给我们的Mergesort功能,我相信我除了我收到的这个错误之外,其他所有其他工作都在程序中:

        incompatible types: Student[] cannot be converted to Comparable[]

我非常感谢对此问题的一些了解,因为我还是Java和OOP的新手。这就是我所拥有的:

TestMergeSort.java:

public class TestMergeSort {

public static void main(String[] args) {
    Student[] students = initializeStudentsArray();

    System.out.println("Displaying students array before sorting...");
    display(students);

    System.out.println("Being sorting...");
    /*
     * The Student array will be sorted by studentId
     * which is declared as a String
     */
    Merge.sort(students); // TODO: Fix the Student class to eliminate this error
    System.out.println("End sorting...");

    System.out.println("Displaying students array after sorting...");
    display(students);
}

private static Student[] initializeStudentsArray() {

    Student[] students = new Student[5];
    students[0] = new Student("Joe", "Jones", "1001");
    students[1] = new Student("Adam", "Ant", "950");
    students[2] = new Student("Bill", "Barnes", "735");
    students[3] = new Student("Mark", "Roth", "1102");
    students[4] = new Student("Jerome", "Howard", "1150");
    return students;

}

private static void display(Student[] students) {
    for (Student std : students) {
        System.out.println("Students [firstName=" + std.firstName + ", lastName=" + std.lastName + ", studentId=" + std.studentId + "]");
    }
}

}

和Student.java:

    public class Student implements Comparator<Student> {

    public String firstName;
    public String lastName;
    public String studentId;

    public Student(String first, String last, String Id) {

        this.firstName = first;
        this.lastName = last;
        this.studentId = Id;
    }

    @Override
    public int compare(Student stud1, Student stud2) {

        String student1 = stud1.studentId;
        String student2 = stud2.studentId;

        return student1.compareTo(student2);
    }
}

我可能正在做一些非常错误的事情,所以请告诉我。非常感谢您的时间!

1 个答案:

答案 0 :(得分:0)

Merge.sort(students);

我不知道Merge课程是什么。我只使用默认的Collections.sort(...)。

public class Student implements Comparator<Student> {

假设它的工作方式与默认的Collections.sort相同,我总是实现Comparable,而不是比较器。

以下示例说明如何为类实现Comparable(非比较器)以及如何创建自定义比较器:

/*
**  Use the Collections API to sort a List for you.
**
**  When your class has a "natural" sort order you can implement
**  the Comparable interface.
**
**  You can use an alternate sort order when you implement
**  a Comparator for your class.
*/
import java.util.*;

public class Person implements Comparable<Person>
{
    String name;
    int age;

    public Person(String name, int age)
    {
        this.name = name;
        this.age = age;
    }

    public String getName()
    {
        return name;
    }

    public int getAge()
    {
        return age;
    }

    public String toString()
    {
        return name + " : " + age;
    }

    /*
    **  Implement the natural order for this class
    */
    public int compareTo(Person p)
    {
        return getName().compareTo(p.getName());
    }

    static class AgeComparator implements Comparator<Person>
    {
        public int compare(Person p1, Person p2)
        {
            return p1.getAge() - p2.getAge();
        }
    }

    public static void main(String[] args)
    {
        List<Person> people = new ArrayList<Person>();
        people.add( new Person("Homer", 38) );
        people.add( new Person("Marge", 35) );
        people.add( new Person("Bart", 15) );
        people.add( new Person("Lisa", 13) );

        // Sort by natural order

        Collections.sort(people);
        System.out.println("Sort by Natural order");
        System.out.println("\t" + people);

        // Sort by reverse natural order

        Collections.sort(people, Collections.reverseOrder());
        System.out.println("Sort by reverse natural order");
        System.out.println("\t" + people);

        //  Use a Comparator to sort by age

        Collections.sort(people, new Person.AgeComparator());
        System.out.println("Sort using Age Comparator");
        System.out.println("\t" + people);

        //  Use a Comparator to sort by descending age

        Collections.sort(people, Collections.reverseOrder(new Person.AgeComparator()));
        System.out.println("Sort using Reverse Age Comparator");
        System.out.println("\t" + people);

        //  Use a Comparator with lambda expression to sort by age

//      Collections.sort(people, (o1, o2) -> o1.getAge() - o2.getAge());
//      Collections.sort(people, Comparator.comparingInt(p -> p.getAge()));
        Collections.sort(people, Comparator.comparingInt(Person::getAge));
        System.out.println("Sort using Lambda Age Comparator");
        System.out.println("\t" + people);
    }
}