简体   繁体   English

如何定义方法 compareTo()?

[英]How to define method compareTo()?

Context:语境:

I have 3 different types of text formatters:我有 3 种不同类型的文本格式化程序:

  1. SnakeCaseFormatter which converts strings eg "Hello World" to "hello_world" SnakeCaseFormatter 将字符串(例如“Hello World”)转换为“hello_world”
  2. KebabCaseFormatter which converts strings eg "Hello World" to "hello-world" KebabCaseFormatter 将字符串(例如“Hello World”)转换为“hello-world”
  3. PascalCaseFormatter which converts strings eg "HellO WoRld" to "HelloWorld" PascalCaseFormatter 将字符串(例如“HellO WoRld”)转换为“HelloWorld”

and these 3 types implements Comparable where TextFormatter is an interface:并且这 3 种类型实现了 Comparable,其中 TextFormatter 是一个接口:

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;我如何实现 compareTo() 方法,以便 compareTo(TextFormatter o) 方法将当前对象与另一个对象进行比较; 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?如果它在另一个对象之前,它返回一个负数,如果它在另一个对象之后返回一个正数,如果它们被认为是相同的顺序,则返回 0?

I assume you want to compare the formatted values.我假设您想比较格式化的值。 Otherwise, like @Mohamed says, the Strings themselves can be compared.否则,就像@Mohamed 所说的,可以比较字符串本身。 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:从 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.您可以在我提供的代码中将它们的值替换为“format()”,但是您希望接口中有一个 getter,以便它可以对存储机制或每个类的细节保持通用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM