简体   繁体   English

说“可比较影响原始类,但比较器不会”,这是什么意思

[英]What does it mean by saying “Comparable affects the original class but Comparator doesnt”

// 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());

Isnt it true that in case 2 the original class is actually modified even though they say Comparator doesnt modify the original class ? 在案例2中,即使他们说Comparator没有修改原始类,实际上是修改了类吗?
May be if i have not understood the concept correctly, do enlighten me on it. 如果我没有正确理解这个概念,可以开导我吧。

Comparable can only ever be implemented on the original class, and so there can only ever be one implementation for it (unless you override compareTo using a subclass). Comparable只能在原始类上实现,因此只能有一个实现(除非你使用子类覆盖compareTo )。 Meanwhile, Comparator is not required to be implemented on the original class, so there can be many implementations. 同时, Comparator不需要在原始类上实现,因此可以有许多实现。

Your second case is quite different from the first case, in that compare will have access to three Dog instances ( this , parameter #1, and parameter #2), while compareTo would have access to only two Dog instances ( this and parameter #1). 你的第二个案例是从第一种情况完全不同,在compare将有机会获得三个Dog实例( this ,参数#1,参数#2),而compareTo将有机会获得仅有的两个Dog实例( this和参数#1 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM