/**
* 泛型 ? 通配符 理解
* ? 可以引用任何类型
* ? 可以使用与参数化 无关的方法
*
* 上边界 ? 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>();
}
/**
* 自定义泛型 与通配符 的理解
* 自定义泛型 可以 使用 与参数化相关 的方法
* 但是不能指 向 任意的 引用类型
* @param collection
* @param t
*/
public static <T> void printCollection2(Collection<T> collection, T t) {
System.out.println(collection.size());
for(Object obj :collection) {
System.out.println(obj);
}
//collection = new HashSet<String>();
//collection = new HashSet<Integer>();
collection.add(t);
}
/**
* 这个方法不可行
* ArrayList<String> = Collection<Object> 编译器不允许你这么玩
* 两边的参数类型 必须一致
* @param collection
*/
public static void printCollection1(Collection<Object> collection) {
}
}
java 自定义泛型 与 通配符的 理解例子
最新推荐文章于 2024-05-27 08:30:00 发布