与泛型类实现可比较 [英] Implementing Comparable with a generic class

查看:217
本文介绍了与泛型类实现可比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个实现泛型Comparable接口的类。在我的课程中,我还定义了一个泛型类型元素 T 。为了实现接口,我将比较委托给 T 。这是我的代码:

  public class Item< T extends Comparable< T>>实现可比< Item> {

private int s;
私人T t;

public T getT(){
return t;
}

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


当我尝试编译它时,我得到以下错误信息:

  Item.java:11:error:方法compareTo在接口Comparable< T#2>不能应用于给定的类型; 
return getT()。compareTo(o.getT());
$
required:T#1
found:Comparable
reason:实际参数Comparable不能通过方法调用转换转换为T#1
其中T#1, T#2是类型变量:
T#1扩展了Comparable< T#1>在类Item中声明
T#2 extends接口中声明的对象Comparable
1错误



<有人可以告诉我为什么以及如何修复它吗?
基本上编译器不能证明泛型类型 o 这个的类型是相同的 T



举例来说,我可以这样做:

 新项目< String>()。compareTo(new Item< Integer>()); 

这显然是错误的,并且是编译器阻止的场景。我认为你只需要nix原始类型:

  public class Item< T extends Comparable< T>> 
实现了Comparable< Item< T>> {



@Override
public int compareTo(Item< T>){
return getT()。compareTo(o。 GETT());
}
}


I want to define a class that implements the generic Comparable interface. While in my class I also defined 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 information:

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 anybody tell me why and how to fix it?

解决方案

Basically the compiler can't prove that the generic type of o is the same T as the type of this.

For example I could do the following:

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

That is clearly wrong and is the scenario the compiler is preventing. I think you just need to nix the raw types:

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

    ...

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

这篇关于与泛型类实现可比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆