Why does this code compile? (java generic method)

144 views Asked by At

The following code:

import java.util.*;

public final class JavaTest {
    public static <T extends Comparable<? super T>> int max(List<? extends T> list, int begin, int end) {
        return 5;
    }

    public static void main(String[] args) {
        List<scruby<Integer>> List = new ArrayList<>();
        JavaTest.<scruby>max(List, 0, 0); //how does this compile?, scruby doesn't meet
        //T extends Comparable<? super T>
    }
}

class scruby<T> implements Comparable<String>{
    public int compareTo(String o) {
        return 0;
    }
}

How does the statement JavaTest.max(List, 0, 0) compile? How does scruby meet the

T extends Comparable <? super T>

It implements Comparable<String> which isn't a super type of scruby? If you change it to scruby<Integer> it won't compile and give the error. So why does it compile now? Why does the raw type compile?

1

There are 1 answers

2
Piotr Praszmo On BEST ANSWER
JavaTest.<scruby>max(List, 0, 0);

scruby is a raw type. This suppresses some of the type checks.

You should add all required type parameters:

JavaTest.<scruby<Integer>>max(List, 0, 0);

Or just let Java infer them:

JavaTest.max(List, 0, 0);