Lists with wildcards cause Generic voodoo error

后端 未结 5 628
梦如初夏
梦如初夏 2020-11-27 17:05

Does anyone know why the following code does not compile? Neither add() nor addAll() works as expected. Removing the \"? extends\" part makes everything work, but then I wou

5条回答
  •  一生所求
    2020-11-27 17:40

    Let me try to explain in what case you might need to use .

    So, lets say you have 2 classes:

    class Grand {
        private String name;
    
        public Grand(String name) {
            this.setName(name);
        }
    
        public Grand() {
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    
    class Dad extends Grand {
        public Dad(String name) {
            this.setName(name);
        }
    
        public Dad() {
        }
    }
    

    And lets say you have 2 collections, each contains some Grands and some Dads:

        List dads = new ArrayList<>();
        dads.add(new Dad("Dad 1"));
        dads.add(new Dad("Dad 2"));
        dads.add(new Dad("Dad 3"));
    
    
        List grands = new ArrayList<>();
        dads.add(new Dad("Grandpa 1"));
        dads.add(new Dad("Grandpa 2"));
        dads.add(new Dad("Grandpa 3"));
    

    Now, lets asume that we want to have collection, which will contain Grand or Dad objects:

            List resultList;
            resultList = dads; // Error - Incompatable types List List
            resultList = grands;//Works fine
    

    How we can avoid this? Simply use wildcard:

    List resultList;
    resultList = dads; // Works fine
    resultList = grands;//Works fine
    

    Notice, that you cant add new items in such (resultList) collection. For more information you can read about Wildcard and PECS conseption in Java

提交回复
热议问题