Java generics, Unbound wildcards <?> vs <Object>

前端 未结 2 905
执念已碎
执念已碎 2020-12-05 10:40

I\'ve read a few topics which cover certain questions about generics, such as their relationship with raw types. But I\'d like an additional explanation on a certain line fo

2条回答
  •  借酒劲吻你
    2020-12-05 11:05

    The sentence that is confusing you is trying to warn you that, while List is the super-type of all generic lists, you cannot add anything to a List collection.

    Suppose you tried the following code:

    private static void addObjectToList1(final List aList, final Object o ) {
        aList.add(o);
    }
    
    private static void addObjectToList2(final List aList, final Object o ) {
        aList.add(o);
    }
    
    private static  void addObjectToList3(final List aList, final T o ) {
        aList.add(o);
    }
    
    
    public static void main(String[] args) {
        List testList = new ArrayList();
        String s = "Add me!";
        addObjectToList1(testList, s);
        addObjectToList2(testList, s);
        addObjectToList3(testList, s);
    }
    
    
    

    addObjectToList1 doesn't compile, because you cannot add anything except null to a List. (That's what the sentence is trying to tell you.)

    addObjectToList2 compiles, but the call to it in main() doesn't compile, because List is not a super type of List.

    addObjectToList3 both compiles and the call works. This is the way to add elements to a generic list.

    提交回复
    热议问题