简体   繁体   English

如何在Java中比较两个值

[英]How can I compare two values in Java

I have a container which can persist values of different types implementing the Comparable interface. 我有一个容器,可以保留实现Comparable接口的不同类型的值。 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. lower通配符的捕获不能转换为upper通配符的捕获,反之亦然。

But how can I solve that issue? 但是我该如何解决这个问题? Any idea? 任何想法?

UPD: The type of the values stored in the container are the same. UPD:容器中存储的值的类型相同。 There is a validation before storing them into it. 在将它们存储到其中之前先进行验证。

What does your class UpperLowerContainer look like? 您的UpperLowerContainerUpperLowerContainer什么样的? You could use type arguments, so that you do not need to use wildcards and casts. 您可以使用类型参数,这样就无需使用通配符和强制类型转换。 For example: 例如:

public class UpperLowerContainer<T extends Comparable<T>> {

    private final T lower;
    private final T upper;

    public UpperLowerContainer(T lower, T upper) {
        this.lower = lower;
        this.upper = upper;
    }

    public T getLower() {
        return lower;
    }

    public T getUpper() {
        return upper;
    }
}

And then: 接着:

Comparable<T> upper = values.getUpper();
Comparable<T> lower = values.getLower();
if (upper.compareTo(lower) < 0) {
    // do something
}

The reason why it doesn't work is because the compiler can't be sure that the two wildcards in these lines refer to the same type: 之所以不起作用,是因为编译器无法确定这些行中的两个通配符是否引用相同的类型:

Comparable<?> upper = (Comparable<?>) values.getUpper();
Comparable<?> lower = (Comparable<?>) values.getLower();

If you call compareTo on one of those comparables, you have to pass it a value of the same type. 如果在这些可比对象之一上调用compareTo ,则必须向其传递一个相同类型的值。 However, because type type is unknown, there's no way for the compiler to check if you pass a value of the right type, so you get an error. 但是,由于类型类型未知,因此编译器无法检查是否传递了正确类型的值,因此会出现错误。

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 将编译

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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