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

      

Isn't it true that in case 2 the original class is actually modified, even though they say the Comparator does not modify the original class?
Maybe if I didn't understand the concept correctly, enlighten me on it.

+3


source to share


1 answer


Comparable

can only be implemented in the original class, so there can only be one implementation for it (unless you override compareTo

with a subclass). Meanwhile, it Comparator

doesn't need to be implemented in the original class, so there can be many implementations.



The second case is very different from the first case, as it compare

will have access to three instances Dog

( this

, parameter # 1 and parameter # 2), while it compareTo

will have access to two instances Dog

( this

and parameter # 1).

+2


source







All Articles