Difference between an unbound wildcard and a raw type

后端 未结 5 536
予麋鹿
予麋鹿 2020-11-27 05:03

I was reading about generics and I did not understand the need for unbound wildcards and how it differs from raw type. I read this question but still did not get it clearly.

5条回答
  •  轮回少年
    2020-11-27 05:18

    How List differs from List

    The main difference is that the first line compiles but the second does not:

    List list = new ArrayList ();
    List list = new ArrayList ();
    
    
    

    However, because you don't know what the generic type of List is, you can't use its parameterized methods:

    List list = new ArrayList ();
    list.add("aString"); //does not compile - we don't know it is a List
    list.clear(); //this is fine, does not depend on the generic parameter type
    

    As for the difference with raw types (no generics), the code below compiles and runs fine:

    List list = new ArrayList ();
    list.add("aString");
    list.add(10);
    

    提交回复
    热议问题