Shy*_*san 5 java collections comparable comparator
// Original class Dog
class Dog{
String name;
int age;
}
//Case 1
class Dog implements Comparable<Dog>{
//compareTo() implementation
}
//Case2
class Dog implements Comparator<Dog>{
// compare() implementation
}
//Case 3
class DogNameComparator implements Comparator<Dog>{
// compare() implementation
}
Collection.sort(dogList);
Collectios.sort(dogList,new DogNameComparator());
Collection.sort(dogList,new Dog());
Run Code Online (Sandbox Code Playgroud)
在情况 2 中,即使他们说 Comparator 没有修改原始类,原始类实际上也被修改了,这不是真的吗?
可能如果我没有正确理解这个概念,请启发我。
Comparable
只能在原始类上实现,因此只能有一种实现(除非您compareTo
使用子类覆盖)。同时,Comparator
不需要在原始类上实现,因此可以有多种实现。
第二种情况与第一种情况有很大不同,因为它compare
可以访问三个Dog
实例(this
参数 #1 和参数 #2),而compareTo
只能访问两个Dog
实例(this
和参数 #1)。
归档时间: |
|
查看次数: |
2019 次 |
最近记录: |