這裏是我的代碼可比比較的Java
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]);
}
}
而且我有一個類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
,但還是老樣子盒實現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?
您對Java中的多態性,繼承和方法重載工作沒有基本知識。先看看這些,然後你就會明白爲什麼:你需要實現compareTo,你可以傳遞不同數量的參數給似乎是相同的方法。 –
你可以參考http://www.digizol.com/2008/07/java-sorting-comparator-vs-comparable.html – lkamal