本文介绍了静态&lt; T扩展数&amp;可比&LT ;?超级号码&gt;&gt;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有一个静态方法的类: public class Helper { public static < T扩展数字&可比< ;?超级号码>>布尔inRange(T值,T minRange,T maxRange){ //等价(值> = minRange&& value< = maxRange) if(value.compareTo(minRange)> = 0&& amp; value.compareTo(maxRange)< = 0) return true; else 返回false; } } 我尝试调用这个方法: 整数值= 2; 整数最小值= 3; 整数最大值= 8; Helper.inRange(value,min,max); Netbeans编译器向我显示以下错误消息: 方法inRange类Helper不能应用于给定的类型; required:T,T,T found:java.lang.Integer,java.lang.Integer,java.lang.Integer reason:推断的类型不符合声明的bound(s )推断:java.lang.Integer bound(s):java.lang.Number,java.lang.Comparable 有什么想法? 谢谢。解决方案试试< T扩展Number&比较< T>> 。 Integer implements Comparable< Integer> ,它与 Comparable (整数不是Number的超类)。 可比< ;? extends Number> 不会工作,因为Java会认为?可以是 Number ,并且传递一个 T 到 compareTo 不会被编译,因为它需要一个 ,而不是 T 。 编辑:如newacct所述,< T extends Number&可比< ;?因为 compareTo 会接受任何?,所以超级T>> / code>其中 T 是一个子类,像往常一样,子类的一个实例可以作为一个参数给予超类。 I have following class with one static method:public class Helper { public static <T extends Number & Comparable<? super Number>> Boolean inRange(T value, T minRange, T maxRange) { // equivalent (value >= minRange && value <= maxRange) if (value.compareTo(minRange) >= 0 && value.compareTo(maxRange) <= 0) return true; else return false; }}I try to call this method:Integer value = 2;Integer min = 3;Integer max = 8;Helper.inRange(value, min, max) ;Netbeans compiler show me this error message: method inRange in class Helper cannot be applied to given types; required: T,T,T found: java.lang.Integer,java.lang.Integer,java.lang.Integer reason: inferred type does not conform to declared bound(s) inferred: java.lang.Integer bound(s): java.lang.Number,java.lang.ComparableAny ideas?thanks. 解决方案 Try <T extends Number & Comparable<T>>.E.g. Integer implements Comparable<Integer>, which is not compatible with Comparable<? super Number> (Integer is not a superclass of Number). Comparable<? extends Number> would not work either because Java would then think the ? could be any subclass of Number, and passing a T to compareTo would then not compile because it expects a parameter of ?, not T.Edit: as newacct said, <T extends Number & Comparable<? super T>> will work too (and be slightly more general) since then compareTo will then accept any ? of which T is a subclass, and as usual, an instance of a subclass can be given as a parameter where a superclass is expected. 这篇关于静态&lt; T扩展数&amp;可比&LT ;?超级号码&gt;&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-14 12:38