简体   繁体   中英

How use relational operators with number generics?

How can I use relational operators with Java number generics?

 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

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.

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.

These reference types are

From type Boolean to type boolean

From type Byte to type byte

From type Short to type short

From type Character to type char

From type Integer to type int

From type Long to type long

From type Float to type float

From type Double to type 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.

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.

The easiest solution would be marking K to extend Number and implement 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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