Java wildcard에 대해
// ============================================
// STUDY: note about wildcard
// ============================================
import java.util.List;
import java.util.ArrayList;
class WildCard {
public static void main(String[] args) {
// Variable is a box that you can put in a data.
//
// And a type is a contraint on what type can be put in.
//
// And List<? extends Number> means
//
// This variable can contain a list that holds any class that extends Number.
//
List<? extends Number> list;
// So, all of these below compiles
list = new ArrayList<Integer>();
list = new ArrayList<Short>();
list = new ArrayList<Long>();
list = new ArrayList<Double>();
list = new ArrayList<Float>();
// But below code doesn't compile.
// list.add(Integer.valueOf(10));
// And why is that? Let's say we decided to put a list that holds floats
List<Float> floats = new ArrayList<Float>();
list = floats;
// But if we add int now, that would mess up that float list.
// list.add(Integer.valueOf(10));
//
// So java compiler prevents us from doing that.
// How about this example?
class Dog {
String name;
Dog(String name) {
this.name = name;
}
void bark() {
System.out.println("bark");
}
}
List<? extends Dog> dogList = new ArrayList<Dog>();
// Below code doesn't compile. Why?
// dogList.add(new Dog("max"));
// Let's declare a new CoolDog class
class CoolDog extends Dog {
CoolDog(String name) {
super(name);
}
void doCoolTrick() {
System.out.println("Did a cool trick");
}
}
// and let's declare two lists
List<CoolDog> coolDogs = new ArrayList<CoolDog>();
List<Dog> lameDogs = new ArrayList<Dog>();
// like we said before, dogList can hold both lameDogs and coolDogs
dogList = lameDogs;
dogList = coolDogs;
// but now if we try to put plain dog into a dogList, that would cause problems
// dogList.add(new Dog("Taffy"));
// see, Taffy is not a CoolDog, so it can't doCoolTrick. Even though underlying coolDogs elements
// are required to doCoolTrick.
//
// So java compiler prevents us from doing that.
}
}