“Comparable 影响原始类,但 Comparator 不影响”是什么意思

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 没有修改原始类,原始类实际上也被修改了,这不是真的吗?
可能如果我没有正确理解这个概念,请启发我。

4ca*_*tle 3

Comparable只能在原始类上实现,因此只能有一种实现(除非您compareTo使用子类覆盖)。同时,Comparator不需要在原始类上实现,因此可以有多种实现。

第二种情况与第一种情况有很大不同,因为它compare可以访问三个Dog实例(this参数 #1 和参数 #2),而compareTo只能访问两个Dog实例(this和参数 #1)。