这是我的代码
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.是否在可比接口(interface)中声明的方法是系统定义的,因为我可以在可比接口(interface)中拥有任何方法,还是只能是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实现了comparator
,但是box仍然实现了comparable
.i.e
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?
最佳答案
为了满足Comparable契约,你必须至少有compareTo方法。您的类中可以有任意多的加法方法。
根据Comparable接口(interface)对元素进行自然排序。所以 sort 是在元素之间调用 compareTo 以查看它们的放置顺序。
为 sort 方法提供一个 Comparator 允许 sort 对 (a) 未实现 Comparable 或(b) 您希望按照类的Comparable 实现所定义的“自然顺序”以外的其他顺序对它们进行排序。
当您传递一个 Comparator 进行排序时,它会调用 Comparator 的比较方法而不是元素的 compareTo 方法(如果已实现)。
参见 Comparator
参见 Comparable
关于java - Comparable 比较器 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7501926/