[英]How use relational operators with number generics?
How can I use relational operators with Java number generics? 如何将关系运算符与Java数字泛型一起使用?
public class Test<K extends Number>{
private K key;
public boolean f (int i){
return i < key; //ERROR
}
public boolean g (K k){
return k < key; //ERROR
}
}
Is there any solution for it? 有什么解决办法吗? compareTo?
相比于?
The Java Language Specification states Java语言规范规定
The type of each of the operands of a numerical comparison operator must be a type that is convertible (§5.1.8) to a primitive numeric type , or a compile-time error occurs.
数值比较运算符的每个操作数的类型必须是可转换(第5.1.8节)为原始数值类型的类型 ,否则会发生编译时错误。
and 和
A type is said to be convertible to a numeric type if it is a numeric type (§4.2), or it is a reference type that may be converted to a numeric type by unboxing conversion.
A型被认为是可转换为数字型 ,如果它是一个数值类型(§4.2),或者它是一个引用类型,其可以被转换成数字类型的取消装箱转换。
These reference types are 这些参考类型是
From type
Boolean
to typeboolean
从类型
Boolean
输入boolean
From type
Byte
to typebyte
从
Byte
类型到byte
类型From type
Short
to typeshort
从
Short
型到short
型From type
Character
to typechar
从
Character
到char
From type
Integer
to typeint
从
Integer
类型到int
类型From type
Long
to typelong
从
Long
型到long
型From type Float to type float
从Float类型到float类型
From type
Double
to typedouble
从
Double
类型到double
类型
Since all you know about K
is that it is a subclass of Number
and therefore not guaranteed to be any of the above, you cannot use a reference of type K
as an operand of the <
operator. 由于您只知道
K
是Number
的子类,因此不能保证是上述任何一个,因此您不能将类型K
的引用用作<
运算符的操作数。
You would have to devise a strategy with the Comparable
interface depending on what you are trying to achieve and how types should be compared. 您必须根据
Comparable
接口以及如何比较类型来设计具有Comparable
接口的策略。
The easiest solution would be marking K
to extend Number
and implement Comparable<K>
: 最简单的解决方案是标记
K
以扩展Number
并实现Comparable<K>
:
public class Test<K extends Number & Comparable<K>>{
private K key;
public boolean f (int i) {
if (!(key instanceof Integer)) {
return false;
}
return new Integer(i).compareTo((Integer)key) < 0;
}
public boolean g (K k){
return k.compareTo(key) < 0;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.