Generics super vs. extends

后端 未结 4 855
情书的邮戳
情书的邮戳 2020-12-30 16:23

Just when I thought I finally understood generics, I came across the following example:

public class Organic {
          void react(E e) { }
            


        
4条回答
  •  执笔经年
    2020-12-30 17:00

    The topic question is also discussed in several other places like:

    • Generic upper bounded wildcard instantiation known at run time
    • Generics with extends
    • CodeRanch: Generics and use of wildcard
    • CodeRanch: Problem in Generics
    • Oracle: Guidelines for Wildcard Use

    It is actually an question from the book for the Java certificate preparation, from the last test (Question 34). The preparation book is based on the lessons book.

    Even with the explanation here and under the other links and the writing in the book the solution was not clear for me because the explanations are mostly based on the List interface and reading that I thought it is some inner collection specific soluton.

    But if you see the definition of the List interface and the add-method on one side and the the Organic class with its react-method on other side you will notice that they are defined in the similar way.

    public interface List extends Collection {
       ...
       boolean add(E e);
       ...
    }
    
    public class Organic {
        ...
        void react(E e) { }
       ...
    }                                               
    

    So all explanation based on the List interface examples which you can find anywhere are valid for this question too.

    List list1 = new ArrayList();
    List list2 = new ArrayList();
    list1.add(new String()); //The method add(capture#1-of ? extends String) in the type List is not applicable for the arguments (String) - // compile-time error
    list2.add(new Object()); //The method add(capture#2-of ? super String) in the type List is not applicable for the arguments (Object) - // compile-time error
    

    Take a look at the explanation on this one:

    • Oracle: Guidelines for Wildcard Use

提交回复
热议问题