Search code examples
javapriority-queuecomparable

How to define method compareTo()?


Context:

I have 3 different types of text formatters:

  1. SnakeCaseFormatter which converts strings e.g. "Hello World" to "hello_world"
  2. KebabCaseFormatter which converts strings e.g. "Hello World" to "hello-world"
  3. PascalCaseFormatter which converts strings e.g. "HellO WoRld" to "HelloWorld"

and these 3 types implements Comparable where TextFormatter is an interface:

interface TextFormatter { 
  public TextFormatter clone(String s);
  public String format();
}

How do I implement the compareTo() method such that the compareTo(TextFormatter o) method compares the current object to another object; It returns a negative number if it comes before the other object, a positive number if it comes after the other object, and 0 if they are considered of the same ordering?


Solution

  • I assume you want to compare the formatted values. Otherwise, like @Mohamed says, the Strings themselves can be compared. This will compare the formatted values:

    interface TextFormatter {
        public TextFormatter clone(String s);
        public String format();
    }
    
    class SnakeCaseFormatter implements TextFormatter, Comparable<TextFormatter> {
    
        ...
    
        @Override
        public int compareTo(TextFormatter other) {
            return format().compareTo(other.format());
        }
    }
    

    You could put this method in your interface as of more recent versions of Java:

    interface TextFormatter extends Comparable<TextFormatter> {
        TextFormatter clone(String s);
        String format();
    
        @Override
        default int compareTo(@NotNull TextFormatter other) {
            return format().compareTo(other.format());
        }
    }
    

    BTW, you don't need the 'public' qualifiers in your interface. Method signatures in an interface have to be public, so that's redundant.

    Maybe you do want to compare the raw strings, for convenience. That's not crazy. I can't write that method for you though, because I don't know how you're storing your strings. You can substitute their values for "format()" in the code I supplied, but you'd want a getter in the interface so it can stay generic to the storage mechanism or the details of each class.