Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

generics

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

A<T extends B> and A<? extends B>
like image 476
arpanoid Avatar asked Mar 06 '11 15:03

arpanoid


People also ask

What is the difference between list <? Super T and list <? Extends T?

extends Number> represents a list of Number or its sub-types such as Integer and Double. Lower Bounded Wildcards: List<? super Integer> represents a list of Integer or its super-types Number and Object.

What does <? Extends mean in Java?

The extends keyword extends a class (indicates that a class is inherited from another class). In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories: subclass (child) - the class that inherits from another class.

What is difference between extends and super in Java?

super is a lower bound, and extends is an upper bound.

What is the difference between and T in Java?

allows you to have a list of Unknown types, where as T requires a definite type. best answer +1 from me!


2 Answers

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

A<T extends B> is a part of generic type declaration such as

public class A<T extends B> { ... }

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<? extends B> is a parameterized type with wildcard, it can be used in variable and method declarations, etc, as a normal type:

A<? extends B> a = ...;

public void foo(A<? extends B> a) { ... }

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

For example, given this declaration

List<? extends Number> l;

you can:

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

    l = new ArrayList<Integer>(); 
    
  • 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
like image 143
axtavt Avatar answered Nov 10 '22 00:11

axtavt


? is what is called a wildcard. It means anything that extends B.

When you write List<T extends String>, your List can contains only elements of type T.

When you write List<? extends String>, your List can contains any element that extends String

I hope I'm clear, since these concepts are complicated.

like image 31
krtek Avatar answered Nov 09 '22 23:11

krtek