Unexpected Conversion Alert

The following code leads to a compiler warning without warning -

{
    List<String> first = first((Class)Integer.class);
}

private <T> List<String> first(Class<T> clazz) { return null; }

However, there are no warnings in the following code -

{
    List<String> second = second((Class)Integer.class);
}

private List<String> second(Class<?> clazz) { return null; }

Only three warnings, the first two I expect, but the third does not make sense -

$ javac Test1.java -Xlint
    Test1.java:6: warning: [unchecked] unchecked conversion
    found   : java.lang.Class
    required: java.lang.Class<T>
    List<String> first = first((Class)Integer.class);
                               ^
    Test1.java:6: warning: [unchecked] unchecked method invocation: <T>first(java.lang.Class<T>) in Test1 is applied to (java.lang.Class)
    List<String> first = first((Class)Integer.class);
                              ^
    Test1.java:6: warning: [unchecked] unchecked conversion
    found   : java.util.List
    required: java.util.List<java.lang.String>
    List<String> first = first((Class)Integer.class);
                              ^
    3 warnings

Compiler Version -

$ javac -version
    javac 1.6.0_45

My question is: why is there a third compiler error?

+4
source share
2 answers

Since you are passing parameters using raw

first((Class)Integer.class)

instead

first((Class<?>)Integer.class)

the return type is firstoverridden in pre-generic Listinstead List<String>, and use List, where List<String>expected, results in an unverified conversion warning.


Java :

, API (, Collections) JDK 5.0. - . :

...

, :

+3

, Class (, , Class<?> Class<Integer>) <T> first, , . , <T>, <String> .

+1

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


All Articles