The difference between List List<Object> List<?>

There is such a point of view: List and List<Object> are the same

actually not.

Analyze from two aspects, 1, type restriction 2, assignment restriction

There is no restriction on the type of List . When add or get, the received or returned object type is Object, so any type of object can be used for add, and the return value type for get is Object. List also has no assignment restrictions , that is, any object that is a collection type can be used, including a type-restricted collection.

List<Object> has type restrictions , the type is restricted to Object, but because Object is the parent of all types, any type of object can be used when adding, and the return value type when getting is also Object. List<Object> also has assignment restrictions. Only collection objects whose type is Object can be assigned to List<Object>.

Consider the following example:

    List<Integer> integerList = new ArrayList<>();
    integerList.add(1);
    integerList.add(2);
    List list = integerList;    //可以赋值List<Integer>
    list.add("String");        //添加String类型的数据
    System.out.println(list);  //输出结果:[1, 2, String]

    List<Object>  objectList = integerList;    //编译报错
    Object[] objectArr = new Integer[]{};      

PS: Look at the last line of the code, arrays are allowed to be assigned in this way

So how do you use List<?>?

List<?> indicates that it can receive any type of collection before it is assigned, but once it is assigned, it can only remove and clear, but not add. It is often used as a parameter to receive an external collection, or to return a collection that does not know the specific type. Look at the following example:

    List<?> list1 = integerList;
    list1.add(3);    //编译报错
    list1.remove(1);
    list1.clear();

 

Guess you like

Origin blog.csdn.net/qq_28411869/article/details/87880039