[英]Why generic constraint T extends Comparable<T> is not sufficient to avoid a cast?
I have a class like this: 我有这样的课:
public class AbstractParameter<T extends Comparable> {
....
public void validate(T tempVal, StringBuilder msg) {
if(tempVal.compareTo(new Integer(0)) != 0 ) {
//do something
}
}
....
}
The tempVal will be an Integer. tempVal将是一个整数。 It compiles and runs fine.
它可以编译并运行良好。 But if I change the T extends Comparable to
T extends Comparable<T>
Above if statement generated the following compile error: 但是,如果我将T扩展Comparable更改为
T extends Comparable<T>
在if语句上方生成以下编译错误:
required: T#1
found: Integer
reason: actual argument Integer 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 AbstractParameter
T#2 extends Object declared in interface Comparable
I can cast the new Integer(0) to T to remove the compile error. 我可以将新的Integer(0) 强制转换为T以消除编译错误。 My question is should I use
public class AbstractParameter<T extends Comparable>
or public class AbstractParameter<T extends Comparable<T>>
? 我的问题是我应该使用
public class AbstractParameter<T extends Comparable>
还是public class AbstractParameter<T extends Comparable<T>>
?
I guess the public class AbstractParameter<T extends Comparable<T>>
should be the way to go but that (T)new Integer(0)
cast seems annoyance. 我猜应该使用
public class AbstractParameter<T extends Comparable<T>>
,但是(T)new Integer(0)
似乎很烦人。 Is there anything wrong in my code? 我的代码有什么问题吗?
Because the type of the parameter to Comparable<T>.compareTo()
is T, and you are sending an integer, which is not compatible. 因为
Comparable<T>.compareTo()
的参数类型为T,并且您正在发送不兼容的整数。 Ask yourself this: if you know that tempVal
is an Integer
, why do you declare it as T? 问问自己:如果您知道
tempVal
是Integer
,为什么tempVal
将其声明为T?
public abstract class AbstractParameter implements Comparable will produce compilation error because inside validate
you are invoking compareTo
on tempVal
and Since there is no Upperbound on T(T can be anything) the compiler can't resolve method tempVal.compareTo(...)
公共抽象类AbstractParameter实现Comparable将产生编译错误,因为在内部
validate
您在tempVal
上调用compareTo
,并且由于T上没有上限(T可以是任何东西),编译器无法解析方法tempVal.compareTo(...)
You mentioned that "The tempVal will be an Integer" in your post. 您在帖子中提到“ tempVal将是一个整数”。 So change the class definition to include this info in order to avoid unchecked warning
因此,请更改类定义以包括此信息,以避免未经检查的警告
public abstract class AbstractParameter<T extends Comparable<Integer>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.