從下面的代碼我不理解兩件事情:的CompareTo()和比較()比較的方法和可比
的
CompareTo()
和Compare()
方法返回int
,但如何影響排序?該方法返回
this.name.compareTo(d.name)
。什麼是this.name
?
請詳細解釋。
import java.util.*;
class Dog implements Comparator<Dog>, Comparable<Dog>{
private String name;
private int age;
Dog(){
}
Dog(String n, int a){
name = n;
age = a;
}
public String getDogName(){
return name;
}
public int getDogAge(){
return age;
}
// Overriding the compareTo method
public int compareTo(Dog d){
return (this.name).compareTo(d.name);
}
// Overriding the compare method to sort the age
public int compare(Dog d, Dog d1){
return d.age - d1.age;
}
}
public class Example{
public static void main(String args[]){
// Takes a list o Dog objects
List<Dog> list = new ArrayList<Dog>();
list.add(new Dog("Shaggy",3));
list.add(new Dog("Lacy",2));
list.add(new Dog("Roger",10));
list.add(new Dog("Tommy",4));
list.add(new Dog("Tammy",1));
Collections.sort(list);// Sorts the array list
for(Dog a: list)//printing the sorted list of names
System.out.print(a.getDogName() + ", ");
// Sorts the array list using comparator
Collections.sort(list, new Dog());
System.out.println(" ");
for(Dog a: list)//printing the sorted list of ages
System.out.print(a.getDogName() +" : "+
a.getDogAge() + ", ");
}
}
無論你在做什麼,這是無稽之談。 '狗'不應該執行'比較器';你應該有一個單獨的類(可能是匿名的)實現'Comparator '。與此同時,你期望'this.name'是什麼?這是這隻狗的名字,與另一隻狗相比。 –
對於'比較',如果狗的年齡相同,它們是相等的。否則,如果第一隻狗比較老,它會返回一個正數,第二隻狗,負數。 – Compass
@louis我對不起你 – Sri