Java generic type casting [duplicate]

This question already has an answer here:

why java compiler (1.8) doesn’t find an error when i use newList1()?

public class Test {

public static void main(String[] args) {
   String str1 = newList1(); //1. it's ok 
   String str2 = newList2(); //2. compiler will warn
}

private static <T extends List> T newList1() {
    return (T) new ArrayList();
}

private static <T extends ArrayList> T newList2() {
    return (T) new ArrayList();
}}

Source: java

Leave a Reply