How to compare two values โ€‹โ€‹in Java

I have a container that can store values โ€‹โ€‹of different types that implement the Comparable interface. I need to compare these 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 } 

Code not compiled for obvious reason. Capturing the wildcard lower cannot be attributed to capturing the upper wildacrd and vice versa.

But how can I solve this problem? Any idea?

UPD: the type of values โ€‹โ€‹stored in the container is the same. Before storage, it has validation.

+2
source share
2 answers

What does your UpperLowerContainer class UpperLowerContainer ? You can use type arguments, so you do not need to use wildcards and throws. For instance:

 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 this does not work is because the compiler cannot be sure that the two wildcards in these lines are of the same type:

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

If you call compareTo on one of these comparable values, you must pass it a value of the same type. However, since the type of the type is unknown, the compiler cannot check if you are passing a value of the correct type so that you receive an error message.

0
source

This code will not compile until you specify the type of object. You cannot use the wild cards that you are trying to use. class declaration should be:

 public class UpperLowerContainer<T extends Comparable<T>> 

and you should use both

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

now you code

 if (upper.compareTo(lower) < 0) { // do something } 

will compile

0
source

Source: https://habr.com/ru/post/988698/


All Articles