Skip to content

Instantly share code, notes, and snippets.

@Arbow
Created May 18, 2011 04:24
Show Gist options
  • Save Arbow/977987 to your computer and use it in GitHub Desktop.
Save Arbow/977987 to your computer and use it in GitHub Desktop.
Java Generic
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<? extends Fruit> list = new ArrayList<Fruit>();
List<? super Apple> list1 = new ArrayList<Apple>();
List<? super Apple> list2 = new ArrayList<Fruit>();
list1.add(new Apple());
list1.add(new Jonathan());
list2.add(new Apple());
list2.add(new Jonathan());
//可见输入类型只跟声明有关,跟具体存储容器无关,只要求容器类型为extends Fruit
ArrayList<Apple> apples = new ArrayList<Apple>();
list2 = apples; //Apple super Apple,合法
list2.add(new Jonathan()); //这里保证了即使list2加入了Apple,Jonathan,apples里面的元素都是Apple子类
list = apples; //Apple extends Fruit,合法
//但此时list不能加任何东西,保证了apples不会被混入Fruit,Object等
ArrayList<Orange> oranges = new ArrayList<Orange>();
//list1 = oranges; //Orange不是Apple父类,非法
list = oranges; //Orange extends Fruit,合法
list.get(0); //返回Fruit实例,由<? extends Fruit>约束,ArrayList<Orange>也保证了返回的肯定是Fruit子类
ArrayList<Fruit> fruits = new ArrayList<Fruit>();
list1 = fruits; //Fruit是Apple父类,合法
list1.add(new Apple());
list1.add(new Jonathan());
fruits.add(new Fruit());
//此时fruits已经有Jonathan/Apple/Fruit这几种类型了
ArrayList<Jonathan> jonathans = new ArrayList<Jonathan>();
// list1 = jonathans; //错误,因为list1能加入apple,会导致jonathans混入Jonathan父类
List<? super Jonathan> list3 = new ArrayList<Jonathan>();
list3 = jonathans;
jonathans.add(new Jonathan());
Object o = list3.get(0); //因为list3可以=apples,所以返回的值只能为object,? super Jonathan可能性为Apple Fruit Object
list = jonathans;
Fruit f = list.get(0);//因为有? extends Fruit保证,所以list元素起码是Fruit类型
//extends约束输出类型,super约束输入类型
}
}
class Fruit {}
class Apple extends Fruit {}
class Orange extends Fruit {}
class Jonathan extends Apple{}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment