简体   繁体   中英

Trouble with a generic comparable in a list

I want to have the following method not show a warning about using raw types, but I can't figure out the syntax to tell it to do what I want. Here is the current method:

static long countSplitInversions(List<? extends Comparable> list) {
    long inversions = 0;

    final int leftLimit = list.size() / 2;
    int left = 0;
    int right = leftLimit;

    for (int i = 0; i < list.size(); i++) {
        if (left == leftLimit || right == list.size()) {
            break;
        }
        if (list.get(left).compareTo(list.get(right)) <= 0) {
            left++;
        } else {
            right++;
            inversions += leftLimit - left;
        }
    }

    return inversions;
}

When I change the signature to avoid the warning to:

static <T> long countSplitInversions(List<? extends Comparable<? super T>> list)

then the line where the compareTo is won't compile with the error:

Method compareTo in interface java.lang.Comparable<T> cannot be applied to given tyes
required: capture #1 of ? super T
found: java.lang.Comparable<? super T>

考虑将您的方法签名更改为类似...

static <T extends Comparable<? super T>> long countSplitInversions(List<T> list) {

Do you mean a warning or compiler error?

You current code already produces a warning, but if you mean a compiler error, as you suggest at the end, then you need to specify a type argument for your Comparable bound.

Somewhat like this will generate a compiler error as you suggest.

static long countSplitInversions(List<? extends Comparable<?>> list) {
 / /...
}

But that would be pointless, you could do nothing with your comparable objects.

As such you may need a type parameter for your method, as the other answer suggest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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