java 如何比较相同类型的泛型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5372659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compare generics of same type?
提问by ColinD
I'm trying to compare two subclasses of Number inside a class with generics. In the code below, I'm trying to compare Number objects inside an instance of Datum.
我正在尝试将类中的 Number 的两个子类与泛型进行比较。在下面的代码中,我试图比较 Datum 实例中的 Number 对象。
How do I enforce that both parameters passed to the Datum constructor are of the same class, so that I can compare what I know to be comparable types - e.g. Float and Float, or Long and Long?
我如何强制传递给 Datum 构造函数的两个参数属于同一类,以便我可以比较我所知道的可比较类型 - 例如 Float 和 Float,或 Long 和 Long?
Float f1 = new Float(1.5);
Float f2 = new Float(2.5);
new Datum<Number>(f1, f2);
class Datum<T extends Number> {
T x;
T y;
Datum(T xNum, T yNum) {
x = xNum;
y = yNum;
if (x > y) {} // does not compile
}
}
回答by ColinD
You could restrict it to Comparable
subclasses of Number
:
您可以将其限制为的Comparable
子类Number
:
class Datum<T extends Number & Comparable<? super T>> {
...
if (x.compareTo(y) > 0) { ... }
}
回答by Pierre
try
尝试
if (((Comparable)x).compareTo((Comparable)y)>0) {}
instead of
代替
if (x > y) {}
回答by BalusC
Compare the outcome of Number#doubleValue()
instead.
比较结果Number#doubleValue()
。
if (x.doubleValue() > y.doubleValue()) {}
回答by Jeff Storey
You could always compare the double values
你总是可以比较双重值
return ((Double)x.doubleValue()).compareTo(y.doubleValue());