Created
March 25, 2011 08:12
-
-
Save JohannesRudolph/886524 to your computer and use it in GitHub Desktop.
A simple example showing common usage scenarios of bounded wildcards in java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Vehicle {} | |
class Car extends Vehicle {} | |
class Porsche extends Car {} | |
public void foo(List<? extends Car> extendsCar , List<? super Car> superOfCar, List<Car> cars) { | |
Vehicle V = new Vehicle(); | |
Car C = new Car(); | |
Porsche P = new Porsche(); | |
// [] specifies the range of valid types for ? | |
// ? extends Car -> [... <: P <: C] <: V | |
extendsCar.add(V); // V <: ?, False | |
extendsCar.add(C); // C <: ?, False | |
extendsCar.add(P); // P <: ?, False | |
V = extendsCar.get(0); // ? <: V, True | |
C = extendsCar.get(0); // ? <: C, True | |
P = extendsCar.get(0); // ? <: P, False | |
// ? super Car -> P <: [C <: V <: ...] | |
superOfCar.add(V); // V <: ?, False | |
superOfCar.add(C); // C <: ?, True | |
superOfCar.add(P); // P <: ?, True | |
V = superOfCar.get(0); // ? <: V, False | |
C = superOfCar.get(0); // ? <: C, False | |
P = superOfCar.get(0); // ? <: P, False | |
} | |
public void bar(){ | |
List<Vehicle> lV = new ArrayList<Vehicle>(); | |
List<Car> lC = new ArrayList<Car>(); | |
List<Porsche> lP = new ArrayList<Porsche>(); | |
foo(lC, lC, lC); // C <: C, C <: C, C :< C | |
foo(lV, lC, lC); // V <: C -> False | |
foo(lP, lC, lC); // P <: C -> True | |
foo(lC, lV, lC); // C <: V -> True | |
foo(lC, lP, lC); // P <: V -> False | |
foo(lC, lC, lV); // List<V> <: List<C> -> False | |
foo(lC, lC, lP); // List<P> <: List<C> -> False | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment