Java – implementation comparable to generic classes

I want to define a class that implements a general comparable interface In my class, I also define a generic type element T. in order to implement the interface, i delegate the comparison to T. here is my code:

public class Item<T extends Comparable<T>> implements Comparable<Item> {

    private int s;
    private T t;

    public T getT() {
        return t;
    }

    @Override
    public int compareTo(Item o) {
        return getT().compareTo(o.getT());
    }
}

When I try to compile it, I get the following error message:

Item.java:11: error: method compareTo in interface Comparable<T#2> cannot be applied to given types;
        return getT().compareTo(o.getT());
                     ^
  required: T#1
  found: Comparable
  reason: actual argument Comparable cannot be converted to T#1 by method invocation conversion
  where T#1,T#2 are type-variables:
    T#1 extends Comparable<T#1> declared in class Item
    T#2 extends Object declared in interface Comparable
1 error

Can someone tell me why and how to solve it?

Solution

Basically, the compiler cannot prove that O's generic type is the same as this type

For example, I can do the following:

new Item<String>().compareTo(new Item<Integer>());

This is obviously wrong and is blocked by the compiler I think you just need to modify the original type:

public class Item<T extends Comparable<T>>
implements Comparable<Item<T>> {

    ...

    @Override
    public int compareTo(Item<T> o) {
        return getT().compareTo(o.getT());
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>