简体   繁体   English

如何将关系运算符与数字泛型一起使用?

[英]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 type boolean 从类型Boolean输入boolean

From type Byte to type byte Byte类型到byte类型

From type Short to type short Short型到short

From type Character to type char Characterchar

From type Integer to type int Integer类型到int类型

From type Long to type long Long型到long

From type Float to type float 从Float类型到float类型

From type Double to type double 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. 由于您只知道KNumber的子类,因此不能保证是上述任何一个,因此您不能将类型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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM