/**
* 泛型 ? 通配符 理解
* ? 可以引用任何类型
* ? 可以使用与参数化 无关的方法
*
* 上边界 ? extends Number 包括自己
*
* 下边界 ? super Integer 包括自己
*
*/
public class GenericTest2 {
public static void main(String[] args) throws Exception {
ArrayList<String> collection2 = new ArrayList<String>();
collection2.add("abc");
collection2.add("efg");
//ArrayList type of Integer
ArrayList<Integer> collection3 = new ArrayList<Integer>();
collection3.add(1);
collection3.add(2);
printCollection(collection2);
printCollection(collection3);
Class<?> x1 = String.class.asSubclass(Number.class);
Class<?> x2 = Class.forName("java.lang.String");
}
public static void printCollection(Collection<?> collection) {
System.out.println(collection.size());
for(Object obj :collection) {
System.out.println(obj);
}
collection = new HashSet<String>();
collection = new HashSet<Integer>();
}
/**
* 这个方法不可行
* ArrayList<String> = Collection<Object> 编译器不允许你这么玩
* 两边的参数类型 必须一致
* @param collection
*/
public static void printCollection1(Collection<Object> collection) {
}
}
java 泛型 通配符 上边界 下边界理解的几个例子1
最新推荐文章于 2025-03-03 23:42:36 发布