What's the difference between unbounded wildcard type List<?> and raw type List?

前端 未结 4 1530
既然无缘
既然无缘 2020-12-01 05:29

Could you help me understand the difference between unbounded wildcard type List and raw type List?

List b;    // unbounded wildca         


        
4条回答
  •  没有蜡笔的小新
    2020-12-01 06:01

    Both cases let us put into this variable any type of list:

    List nothing1 = new ArrayList();
    List nothing2 = new ArrayList();
    List nothing3 = new ArrayList<>();
    List nothing4 = new ArrayList();
    
    List wildcard1 = new ArrayList();
    List wildcard2 = new ArrayList();
    List wildcard3 = new ArrayList<>();
    List wildcard4 = new ArrayList();
    

    But what elements can we put into this objects?

    We can put only String into List:

    List strings = new ArrayList<>();
    strings.add("A new string");
    

    We can put any object into List:

    List nothing = new ArrayList<>();
    nothing.add("A new string");
    nothing.add(1);
    nothing.add(new Object());
    

    And we can't add anything (but for null) into List! Because we use generic. And Java knows that it is typed List but doesn't know what type it is exact. And doesn't let us make a mistake.

    Conclusion: List, which is generic List, gives us type safety.

    P.S. Never use raw types in your code.

提交回复
热议问题