Why is this code compiling? (java generic method)

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 is the JavaTest.max (List, 0, 0) operator compiled? How scruby meets

T extends Comparable <? super T>

Comparable<String>Does it implement that is not a super-type of scruby? If you change it to scruby<Integer>, it will not compile and will throw an error. So why is it compiling now? Why is the source type compiled?

+4
source share
1 answer
JavaTest.<scruby>max(List, 0, 0);

scrubyis a raw type. This suppresses some type checking.

You must add all the required type parameters:

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

Or just let Java output them:

JavaTest.max(List, 0, 0);
+3
source

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


All Articles