Giu_ai
Giu_ai

Reputation: 183

Extending Comparable in a generic class

I am new to Java and I have a problem. I need a class to store two values, one called key and one called value. The class can store the objects, return value and allow comparison between two objects by comparing the key 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. I am allowed to use equalsTo(Object) as well. How can I implement 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 <.

Upvotes: 0

Views: 4281

Answers (1)

Boris the Spider
Boris the Spider

Reputation: 61148

The other answers here seem to be very confused as to generics and the 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; you then use its compareTo method to compare your Entry to the other Entry based on the keys.

Upvotes: 6

Related Questions