Java 扩展可比较的接口并覆盖 compareTo

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20214308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 00:21:44  来源:igfitidea点击:

Extending comparable interface and override compareTo

javainterfacecomparablecompareto

提问by Alexej Geldt

I know this has propably been asked 1000 times, and i have seen 1000 answers, but i didn't see any that actually worked for me.

我知道这可能被问了 1000 次,我看到了 1000 个答案,但我没有看到任何对我有用的答案。

I have to sort a List of objects which implement my own interface. I decided to extend Comparable interface and implement compareTo method for those objects.

我必须对实现我自己的接口的对象列表进行排序。我决定扩展 Comparable 接口并为这些对象实现 compareTo 方法。

my interface:

我的界面:

public interface Field extends Comparable<Field> {

}

my object class

我的对象类

public class ConcreteField implements Field {

    public int compareTo(Field other){
        return this.getName().compareTo(other.getName());
    }    
}

This doesn't work as i would expect.

这不像我期望的那样工作。

Compiler seems to recognize that the ConcreteField must implement compareTo. Thats fine.

编译器似乎认识到 ConcreteField 必须实现 compareTo。没关系。

With example above i can compare ConcreteField objects. But not when they are represented by their interface (Field).

通过上面的例子,我可以比较 ConcreteField 对象。但不是当它们由它们的接口(字段)表示时。

I can sort a List of ConcreteField's but i cannot sort a List of Field's. Of course this is naturaly, since the implementation of compareTo is in ConcreteField, but i was expecting that java would call compareTo on each concrete object which implements Field. Seems not to be the case.

我可以对 ConcreteField 的列表进行排序,但无法对 Field 的列表进行排序。当然,这是很自然的,因为 compareTo 的实现在 ConcreteField 中,但我希望 java 会在每个实现 Field 的具体对象上调用 compareTo。似乎并非如此。

But then, how do you actually sort objects which are represented by their comparable interface?

但是,您实际上如何对由其可比接口表示的对象进行排序?

Another strange things that i just dont get.

另一个奇怪的事情,我就是不明白。

Using @Override over compareTo method makes the compiler yelling: The method compareTo(Field) of type ConcreteField must override or implement a supertype method. Huh? There is no supertype, its just implementing an interface.

在 compareTo 方法上使用 @Override 会使编译器大喊大叫: ConcreteField 类型的 compareTo(Field) 方法必须覆盖或实现超类型方法。嗯?没有超类型,它只是实现了一个接口。

When i remove compareTo from ConcreteField class. Compiler complains that it must be implemented. When i use eclipse quickfix, which says "implement missing methods", it fails to do so and tells me "Cannot implement the missing methods, either due to compiler errors or the project build path does not resolve all dependencies".

当我从 ConcreteField 类中删除 compareTo 时。编译器抱怨它必须被实现。当我使用 eclipse quickfix 时,它说“实现缺少的方法”,它没有这样做并告诉我“无法实现缺少的方法,要么由于编译器错误,要么项目构建路径没有解决所有依赖项”。

There is no dependency at all. Its all in the same project and even same package. So what the hell is wrong with this?

完全没有依赖性。它都在同一个项目中,甚至在同一个包中。那么这到底有什么问题呢?

采纳答案by Nishant Lakhara

@Masud : Implementation suggested by you (Post deleted)

@Masud:您建议的实施(帖子已删除)

Create an interface like :

创建一个接口,如:

public interface Field<T> extends Comparable<T> {
    public String getName();
}

Create a ConcreteField class like :

创建一个 ConcreteField 类,如:

import java.util.Arrays;


public class ConcreteField implements Field<Field>{

    private String name;

    @Override
    public int compareTo(Field other) {
        return this.name.compareTo(other.getName());
    }

    @Override
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public static void main(String[] args) {
        ConcreteField[] c = new ConcreteField[3];
        c[0] = new ConcreteField();
        c[1] = new ConcreteField();
        c[2] = new ConcreteField();
        c[0].setName("c");
        c[1].setName("b");
        c[2].setName("a");

        Arrays.sort(c);
        for(int i=0;i<c.length;i++) {
            System.out.println(c[i].getName());
        }

    }
}

The output I am getting is sorted.

我得到的输出已排序。

a
b
c

回答by Abhijith Nagarajan

Please find below my code and explanation.

请在下面找到我的代码和解释。

public interface Field extends Comparable<Field> {
}

Interface implements Comparable interface. Below is the implementation.

接口实现了 Comparable 接口。下面是实现。

Java always looks at the type referenced. If you are referring to a object via interface, then you would see only the methods in the interface and constants.

Java 总是查看引用的类型。如果您通过接口引用对象,那么您只会看到接口中的方法和常量。

Let me know if you have any questions.

如果您有任何问题,请告诉我。

public class ConcreteField implements Field {

private String name;

/**
 * @return the name
 */
public String getName() {
    return name;
}

public ConcreteField(String name) {
    this.name = name;
}

@Override
public int compareTo(Field o) {
    ConcreteField cf = (ConcreteField) o;
    return this.getName().compareTo(cf.getName());

}

public static void main(String[] args) {

    List<Field> list = new ArrayList<Field>();
    list.add(new ConcreteField("test"));
    list.add(new ConcreteField("abc"));
    list.add(new ConcreteField("dec"));
    list.add(new ConcreteField("mef"));
    list.add(new ConcreteField("keg"));
    list.add(new ConcreteField("sdf"));
    list.add(new ConcreteField("abc"));

    System.out.println(list);

    Collections.sort(list);

    System.out.println(list);

}

/*
 * (non-Javadoc)
 * 
 * @see java.lang.Object#toString()
 */
@Override
public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append("ConcreteField [name=");
    builder.append(name);
    builder.append("]");
    return builder.toString();
}

}