我如何比较Java中的两个值 [英] How can I compare two values in Java
问题描述
我有一个容器可以保存实现 Comparable
接口的不同类型的值。我需要比较这些值如下:
UpperLowerContainer值;
//初始化容器
可比较<?> upper =(可比较的<>)values.getUpper();
可比较<?> lower =(可比较的<>)values.getLower();
if(upper.compareTo(lower)<0){//这不是编译
//做一些
}
由于显而易见的原因,代码未被编译。捕获 lower
的通配符不能转换为捕获 upper
的wildacrd,反之亦然。 / p>
但我该如何解决这个问题?任何想法?
UPD:存储在容器中的值的类型是相同的。在将它们存储到它之前有一个验证。
除非您不指定对象的类型,否则给定代码将不会编译。您正尝试使用不能使用通配符。
类声明应该是:
public class UpperLowerContainer< T extends Comparable< T>>
,您应该像
可比< T> upper = values.getUpper();
比较< T> lower = values.getLower();
现在您的代码
if(upper.compareTo(lower)<0){
//做某事
}
会编译
I have a container which can persist values of different types implementing the Comparable
interface. I need to compare those values as follows:
UpperLowerContainer values;
//initializing the container
Comparable<?> upper = (Comparable<?>) values.getUpper();
Comparable<?> lower = (Comparable<?>) values.getLower();
if (upper.compareTo(lower) < 0){ //This is not compiled
//do some
}
The code is not compiled because of the obvious reason. The capture of the lower
's wildcard cannot be cast to the capture of upper
's wildacrd and vice versa.
But how can I solve that issue? Any idea?
UPD: The type of the values stored in the container are the same. There is a validation before storing them into it.
Given code will not compile until you will not specify type of object. You can not use wild cards as you are trying to use. class declaration should be:
public class UpperLowerContainer<T extends Comparable<T>>
and you should use like
Comparable<T> upper = values.getUpper();
Comparable<T> lower = values.getLower();
now you code
if (upper.compareTo(lower) < 0) {
// do something
}
will compile
这篇关于我如何比较Java中的两个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!