1

I tried to add interface Comparable to class SimpleEntry by subclass it. Because SimpleEntry is a generic type, I used this:

public class SimpleEntryComparable<K, V> extends SimpleEntry<K, V> implements
        Comparable<T> {

    public SimpleEntryComparable(K arg0, V arg1) {
        super(arg0, arg1);
        // TODO Auto-generated constructor stub
    }
}

And eclipse complained "T cannot be resolved to a type". I'm confused about subclass a generic class and add interfaces... anyone can tell me something about this?

Lingfeng Xiong
  • 1,131
  • 2
  • 9
  • 25

2 Answers2

2

The <T> on Comparable tells the compiler what type the class can be compared to. In your case, if you want to be able to compare to other SimpleEntryComparables, you just need implements Comparable<SimpleEntryComparable<K,V>> (and compareTo, of course!).

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
  • Thank you. But in compareTo(), I want to "return o.getKey() - this.getKey();". However, the type of Key/Value are generic and this statement just failed. What shall I do? – Lingfeng Xiong Sep 07 '13 at 23:19
  • You can't ever subtract objects in Java, only primitives. If you're trying to make your entries `Comparable`, you have to be able to describe the order they should go in. If you can't, then instead of a `SimpleEntryComparable`, you should just write a `Comparator>`. – chrylis -cautiouslyoptimistic- Sep 07 '13 at 23:47
2

chrylis' answer is correct. Below it I see you have this comment:

But in compareTo(), I want to "return o.getKey() - this.getKey();"

Based on this comment, it sounds like you want the following:

public class SimpleEntryComparable<K extends Comparable<? super K>, V>
extends SimpleEntry<K, V>
implements Comparable<SimpleEntryComparable<K, V>> {

    @Override
    public int compareTo(final SimpleEntryComparable<K, V> other) {
        return getKey().compareTo(other.getKey());
    }
}

This ensures that K is comparable to itself (or some super-type of itself), so that your code can delegate to that type's compareTo implementation. This is the only way to do generic comparisons of reference types - as chrylis points out, arithmetic operations are only supported for primitives.

Community
  • 1
  • 1
Paul Bellora
  • 54,340
  • 18
  • 130
  • 181