我有下面的类声明中的方法:Java错误传递参数给接受其中T延伸可比<T>
public class UserVariable<T extends Comparable<T>> implements Comparable<UserVariable<T>>
{
private T myValue;
public void setValue(T value)
{
myValue = value;
}
public T getValue()
{
return myValue;
}
public int compareTo(UserVariable<T> rhs)
{
return getValue().compareTo(rhs.getValue());
}
}
如果我做了正确的,我想要的东西是:UserVariable
可以比其他UserVariable
s并且它是通用的并且接受可以与其他T
s进行比较的类型T
。
我有麻烦调用setValue()
,并传递一个整数:
UserVariable<Integer> newVar = new UserVariable<Integer>();
newVar.setValue(new Integer(20));
给我的错误“的方法setValue(Comparable<Comparable<T>>)
在类型UserVariable<Comparable<Comparable<T>>>
不适用于参数(Integer
)”。
我不明白为什么我得到这个错误。首先,Integer
执行Comparable<Integer>
。其次,为什么Comparable
在错误消息中以嵌套的方式出现了两次(Comparable<Comparable<T>>
)?是的,UserVariable
也实现了Comparable
,但错误是指方法参数的类型,它的类型是T
,它应该是T extends Comparable<T>
,对吧?
UPDATE:
我已经意识到了问题的事实,我从一个通配符检索集合对象连接:
Map<String, UserVariable<?>> myVars = new HashMap<>();
UserVariable<Double> v1 = new UserVariable<>();
v1.setValue(3.0);
myVars.put("doubleVar", v1);
myVars.get("doubleVar").setValue(new Double(30));
添加上面的代码将重现的编译错误最后一行。
我很抱歉,恐怕问题的范围已经完全改变了最新的信息,因为我正在从UserVariable<?>
类型的地图中拉出一个对象,并试图对此致电setValue()
。
您应该使用'>',但是看到那'Integer'暗示'Comparable '而不是'Comparable '这不太可能是你问题的根源。 –
kajacx
'public setValue'应该是'public void setValue'。否则,在实现compareTo之后,我可以调用'setValue(new Integer(20))'而不会出现错误 –
可能的重复项:http://stackoverflow.com/questions/5013947/create-a-compareto-to-a-generic- class-that-implement-comparable,http://stackoverflow.com/questions/21544716/implementing-comparable-with-a-generic-class – cuddlecheek