简体   繁体   中英

Java generics query (Upper Bounded Wildcards)

Consider below scenario, Class FastCar extends from Car Class:

public class FastCar extends Car {}

Code snippet in main method:

Set<? extends Car> mySet6 = null;
mySet6.add(new FastCar()); //<-----compile error  

Compile Error Details:

(The method add(capture#4-of ? extends Car) in the type Set<capture#4-of ? 
extends Car> is not applicable for )

I'm confused why FastCar object can't put into the "set of object extends Car", anyone can help to clarify? Thanks.

The purpose of generics is to provide type-safe operations (and disallow non-type-safe operations).

For a variable of type Set<? extends Car> Set<? extends Car> the compiler allows to assign a value of type Set<SlowCar> because Set<SlowCar> extends Set<? extends Car> Set<? extends Car> . If you would do this, adding a FastCar to a Set allowing only SlowCar s would obviously be an error. Therefore adding a FastCar to a Set allowing ? extends Car ? extends Car must also not be allowed because it is not type-safe.

Set<SlowCar> slowSet = ...;

slowSet.add(new FastCar()); // Obviously ERROR, FastCar does not extend SlowCar

Set<? extends Car> carSet = slowSet; // Allowed, valid (SlowCar extends Car)

carSet.add(new FastCar());   // Error, because carSet might be
                             // and actually is a set of SlowCars

In your case Set<Car> should be used:

Set<Car> cars = ...;

cars.add(new FastCar());   // Valid, FastCar extends Car
cars.add(new SlowCar());   // Valid, SlowCar extends Car

This case is good explained in Java Tutorials about wildcars . I will just reformulate it (I renamed types and objects names):

You should be able to figure out why the code above is disallowed. The type of the parameter to mySet6.add() is ? extends Car ? extends Car -- an unknown subtype of Car . Since we don't know what type it is, we don't know if it is a supertype of FastCar ; it might or might not be such a supertype, so it isn't safe to pass a FastCar there.

http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html

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