这是我的代码
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?