Search code examples
javatreeset

TreeSet comparator OR comparble.compareTo() priority


If the Java TreeSet is set with a comparator to deal with the objects sorting logic But the objects ( class) also implements comparable and have valid compareTo method implemented on it.

Which one takes priority? The logic within the comparator or the logic in the compareTo method?

Many thanks.


Solution

  • The Comparator passed-in to TreeSet's constructor takes priority. This allows for using a different comparison algorithm than is implemented by the object's compareTo. If it weren't for this, you'd never be able to use a different comparison algorithm with TreeSet.