简体   繁体   中英

Generics wildcard confusion

What is the functional difference between

Container<Class>

and

Container<? extends Class>

?

Anything that inherits from Class is a Class so I don't understand why bother with ? .

Since the Class class is final , the <? extends Class> <? extends Class> will be applicable only for the Class type.

Therefore, there's no functional difference between Container<Class> and Container<? extends Class> Container<? extends Class> .

Update : If your question refers to What is a wildcard ? and if we assume we're not talking about Class , but some other (extendable) type, here's the difference:

Let's say we have two classes:

  • class Shape
  • class Rectangle extends Shape

Consider the following method signature:

public void addRectangle(List<? extends Shape> shapes)

This is an example of bounded wildcard , where the Shape part is called upper bound .

public void addRectangle(List<? extends Shape> shapes) {
    // Compile-time error!
    shapes.add(0, new Rectangle());
}

The reason for the compile-time error is that the type of the second parameter to shapes.add() is ? extends Shape ? extends Shape , which in human language means an unknown subtype of Shape . Since we don't know what type it is, we don't know if it is a supertype of Rectangle . It might or might not be such a supertype, so it isn't safe to pass a Rectangle there.

The example is taken from:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM