第8章 泛型
public static void main(String[] args) {
List<String> a1 = new ArrayList<String>();
List<Integer> a2 = new ArrayList<Integer>();
System.out.println(a1.getClass());
a1.add("xiaoxiao");
test(a1);
}
public static void test(List<Object> c){ //这样会报错
for(int i=0;i<c.size();i++){
System.out.println(c.get(i));
}
}
可以使用通配符:
public static void main(String[] args) {
List<String> a1 = new ArrayList<String>();
List<Integer> a2 = new ArrayList<Integer>();
System.out.println(a1.getClass());
a1.add("xiaoxiao");
test(a1);
}
public static void test(List<?> c){ //这样会报错
for(int i=0;i<c.size();i++){
System.out.println(c.get(i));
}
}
8.3.2 设定类型通配符的上限
public void drawAll(List<? extends Shape> shapes) {
// TODO Auto-generated method stub
for(Shape shape : shapes){
shape.draw(this);
}
}