What is the difference between A and A<? extends B>?

后端 未结 4 1883
借酒劲吻你
借酒劲吻你 2020-12-23 10:57

I am a new java learner. Recently I was reading Generic programming and got my self confused with this...

A and A
         


        
4条回答
  •  自闭症患者
    2020-12-23 11:20

    First of all, those are completely different constructs used in different contexts.

    A is a part of generic type declaration such as

    public class A { ... }
    

    It declares generic type A with type parameter T, and introduces a bound on T, so that T must be a subtype of B.


    A is a parameterized type with wildcard, it can be used in variable and method declarations, etc, as a normal type:

    A a = ...;
    
    public void foo(A a) { ... }
    

    Variable declaration such as A a means that type of a is A parameterized with some subtype of B.

    For example, given this declaration

    List l;
    

    you can:

    • Assign a List of some subtype of Number to l:

      l = new ArrayList(); 
      
    • Get an object of type Number from that list:

      Number n = l.get(0);
      

    However, you can't put anything into list l since you don't know actual type parameter of the list:

    Double d = ...;
    l.add(d); // Won't compile
    

提交回复
热议问题