简体   繁体   English

在泛型类中扩展Comparable

[英]Extending Comparable in a generic class

I am new to Java and I have a problem. 我是Java新手,但遇到了问题。 I need a class to store two values, one called key and one called value . 我需要一个类来存储两个值,一个称为key ,一个称为value The class can store the objects, return value and allow comparison between two objects by comparing the key value. 该类可以存储对象,返回value并可以通过比较键值来允许两个对象之间的比较。

public class Entry <K,V> implements Comparable<Entry<K,V>> 
{
    private K key;
    private V value;

    public Entry(K key,V value)
    {
        this.key=key;
        this.value=value;
    }

    public void setValue(V value)
    {
        this.value=value;
    }

    public String toString()
    {
        return "key= "+key+" value=" +value;
    }
}

He is now asking me to add the Comparable method. 他现在要我添加Comparable方法。 I am allowed to use equalsTo(Object) as well. 我也被允许使用equalsTo(Object) How can I implement Comparable ? 如何实现Comparable I tried 我试过了

public Comparable(k key)
{
    if (this.k < k)
        return -1; 

    if (this.k > k)
        return 1;

    else return 0;
}

but I got an error saying that I am not allowed to use > or < . 但是我收到一个错误,说我不允许使用><

The other answers here seem to be very confused as to generics and the Comparable interface . 对于泛型和Comparable interface这里的其他答案似乎很困惑。

Here is some code that will compile: 这是一些可以编译的代码:

public class Entry<K extends Comparable<K>, V> implements Comparable<Entry<K, V>> {

    private final K key;
    private V value;

    public Entry(K key, V value) {
        this.key = key;
        this.value = value;
    }   

    @Override
    public int compareTo(Entry<K, V> other) {
        return key.compareTo(other.key);
    }
}

So you force the type of your key to also extend Comparable to itself; 因此,您强制密钥的类型也将Comparable扩展为自身。 you then use its compareTo method to compare your Entry to the other Entry based on the keys. 然后,您可以使用其compareTo方法根据键将您的Entry与其他Entry进行比较。

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

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