Java Generics (Wildcards)

后端 未结 6 1499
轻奢々
轻奢々 2020-11-22 10:17

I have a couple of questions about generic wildcards in Java:

  1. What is the difference between List and List

6条回答
  •  太阳男子
    2020-11-22 11:01

    In general,

    If a structure contains elements with a type of the form ? extends E, we can get elements out of the structure, but we cannot put elements into the structure

    List ints = new ArrayList();
    ints.add(1);
    ints.add(2);
    List nums = ints;
    nums.add(3.14); // compile-time error
    assert ints.toString().equals("[1, 2, 3.14]"); 
    

    To put elements into the structure we need another kind of wildcard called Wildcards with super,

     List objs = Arrays.asList(2, 3.14, "four");
        List ints = Arrays.asList(5, 6);
        Collections.copy(objs, ints);
        assert objs.toString().equals("[5, 6, four]");
    
        public static  void copy(List dst, List src) {
              for (int i = 0; i < src.size(); i++) {
                    dst.set(i, src.get(i));
             }
        }
    
        

    提交回复
    热议问题