I have an abstract class looks like this.
abstract class Some {
int rank;
}
Now I want to define a static variable and/or method of comparing the rank
.
static <T extends Some> Compartor<T> comparingRank() {
return Comparator.compartingInt(Some::getRank);
}
static final Compartor<Some> COMPARING_RANK
= Compartor.comparingInt(Some::getRank);
My questions are...
- Should I use
<? super T>
forcomparingRank()
method? - Should I use
<? super T>
forCOMPARING_RANK
field?
CodePudding user response:
We generally don't encourage to use wildcards in the return type of the method, since that renders the method unusable. So, the first option is ruled out due to that.
The second variant of using a lower bound wildcard ? super T
is generally a good thing which makes your API much more flexible. But, in this particular scenario, the comparingInt
declares that wildcard, leaving yours superfluous.
static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor)
Thus, in my opinion, you can keep it as it is without any modification. However, you may still use the wildcard where circumstances warrant.