1

这是我的代码

class ComparableTest
{
    public static void main(String[] args)
    {
        BOX[] box = new BOX[5];
        box[0] = new BOX(10,8,6); 
        box[1] = new BOX(5,10,5);
        box[2] = new BOX(8,8,8);
        box[3] = new BOX(10,20,30);
        box[4] = new BOX(1,2,3);
        Arrays.sort(box);
        for(int i=0;i<box.length;i++)
            System.out.println(box[i]);
    }
}

我还有一个实现 Comparable 的类 BOX。现在我有几个问题希望大家帮助我解决。

1.是否在可比较接口中声明的方法,系统已定义,如我可以在可比较中使用任何方法,还是必须compareTo只有?

2.我没有提供Arrays.sort方法的实现,那它是如何对我的元素进行排序的呢?

3.当我使用Comparator代替时comparable,我使用:

class comparatorTest
{
    public static void main(String args[])
    {
        Student[] students = new Student[5];
        Student[0] = new Student(“John”,”2000A1Ps234”,23,”Pilani”);
        Student[1] = new Student(“Meera”,”2001A1Ps234”,23,”Pilani”);
        Student[2] = new Student(“Kamal”,”2001A1Ps344”,23,”Pilani”);
        Student[3] = new Student(“Ram”,”2000A2Ps644”,23,”Pilani”);
        Student[4] = new Student(“Sham”,”2000A7Ps543”,23,”Pilani”);    
        // Sort By Name
        Comparator c1 = new studentbyname();
        Arrays.sort(students,c1);
        for(int i=0;i<students.length;i++)
            System.out.println(students[i]);
    }
}

//在上面的代码中studentbyname implements comparator,,但是box仍然实现comparable了.ie

class studentbyname implements comparator
{
    public int compare(Object o1,Object o2)
    {  
        Student s1 = (Student) o1;
        Student s2 = (Student) o2;
        return s1.getName().compareTo(s2.getName());
    }
}

现在我在做Arrays.sort(students,c1),为什么我现在要通过c1?

4

3 回答 3

3
  1. 为了满足Comparable契约,你必须至少有compareTo方法。您可以在您的班级中拥有任意数量的添加方法。

  2. 它基于Comparable接口以自然顺序对元素进行排序。所以sort在元素之间调用compareTo以查看放置它们的顺序。

  3. 为 sort 方法提供一个Comparator允许sort对以下元素进行排序:(a) 不实现Comparable或 (b) 您希望以不同于类的Comparable实现所定义的“自然顺序”的其他顺序对它们进行排序。

当您将 Comparator 传递给排序时,它会调用 Comparator 的 compare 方法而不是元素的 compareTo 方法(如果已实现)。

看看什么是接口

比较器

可比

于 2011-09-21T14:58:59.370 回答
1
  1. Comparable只要你实现了,你就可以在 a 中定义任意数量的方法compareTo。此方法可用于检查类进行比较的许多情况。例如,将实例插入有序的TreeSet. compareTo为类的所有实例提供一般排序规则。
  2. Arrays.sort orders the array in the natural order of its elements. That is, using compareTo.
  3. You can use Comparator to define a custom ordering rule. Like when you have a table you can sort by any of its columns. You could define a Comparator for each of its columns, and you could still have a class-inherent ordering rule (as in related to the reality the Class represents) defined in the class' compareTo.
于 2011-09-21T15:01:30.733 回答
0

实现Comparable要求您提供compareTo()的实现。

传递给Arrays.sort(Object[])方法的 Object 数组中的所有元素都必须实现Comparable。如果要改用Comparator,则必须使用以 a作为参数的Arrays.sort()方法。Comparator您在上面的示例中使用的方法将 aComparator作为第二个参数 - 因此需要c1在方法调用中提供。

于 2011-09-21T14:59:26.280 回答