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.
source share