-3

This question was asked in an interview. The question was why String and other wrapper classes implement Comparable instead of Comparator interface. I tried to explain that Comparator is basically to provide customized sorting and Comparable is for default natural sorting order. Also from design principle perspective, Comparable is tightly coupled and Comparator is loosely coupled. However, I could not clarify why String implemented Comparable instead of Comparator.

user207421
  • 305,947
  • 44
  • 307
  • 483
RoyalTiger
  • 511
  • 2
  • 8
  • 27
  • Other semi-duplicates: "[When should a class be Comparable and/or Comparator?](https://stackoverflow.com/questions/1440134)" and "[What is the difference between compare() and compareTo()?](https://stackoverflow.com/questions/420223)". Unfortunately, there's no canonical dup-target question for this... just a handful of moderately upvoted mutual duplicates. – Kevin J. Chase Aug 23 '16 at 04:25

1 Answers1

4

Strings implement Comparable because they are things that can be compared. In general, things that implement Comparable tend to have a natural ordering, like you mentioned.

A Comparator is a way of comparing things. When you make a Comparator, you're defining a method with which to compare things. You can make many Comparators on a given type to compare things in different ways.

John
  • 2,575
  • 1
  • 17
  • 29
  • I mentioned something about natural ordering above. Yes, but I think we can easily modify this ordering by overriding the compareTo() method. I mean this varies from implementation to implementation . It's not specific to Comparable or Comparator. String is a mutable class and implemented in such a way that it always gives you natural order sort. – RoyalTiger Aug 28 '16 at 01:35
  • You can modify the ordering by overriding compareTo, but for each class implementing Comparable you can only have one defined ordering, because you have to pick a particular way to write compareTo. However, you can make several Comparators that compare objects of a particular class, each of which can define different orderings. Check out the other comparable vs comparator questions for more info as well. – John Aug 29 '16 at 02:55