Difference between an unbound wildcard and a raw type

后端 未结 5 534
予麋鹿
予麋鹿 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:24

    List is useful in a method signature to call methods that never require the type parameter, i.e., read from the list or rotate it, for instance.

    void someMethod(List list) {
      list.clear();  // I will never add anything to the list in here
    }
    

    You will never add anything or otherwise modify the list with respect to the type it holds as you cannot add anything to the list except null in methods with this signature and thus you won't ever break type safety. Raw List on the other hand you can do anything to, which as we all know can result in a type safety violation.

    void someMethod2(List list) {
     list.add(new WeaselFurBrush());  
    }
    List list1 = new ArrayList();
    someMethod2(list1);// oops
    

提交回复
热议问题