Shyam Sreenivasan
Shyam Sreenivasan

Reputation: 51

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 ?
May be if i have not understood the concept correctly, do enlighten me on it.

Upvotes: 5

Views: 2154

Answers (1)

castletheperson
castletheperson

Reputation: 33466

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). Meanwhile, Comparator is not required to be implemented on the original class, so there can be many implementations.

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).

Upvotes: 3

Related Questions