package test1;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
//泛型应用
public class GenericTest {
public static void main(String[] args) {
Date date = new Date();
Collection<Integer> arr = new ArrayList<Integer>();
Collection<Object> arr2 = new ArrayList<Object>();
arr.add(3);
arr.add(4);
arr2.add(new Object());
arr2.add(new Object());
//printCode1(arr);
printCode2(arr);
printCode1(arr2);
printCode2(arr2);
}
public static void printCode1(Collection<Object> cols){
for(Object obj: cols){
System.out.println(obj);
}
//cols.add(“string”);//没错
//cols = new HashSet<Date>();//报错
cols = new HashSet<Object>();//没错,这还可以理解
}
public static void printCode2(Collection<?> cols){
for(Object obj: cols){
System.out.println(obj);
}
//cols.add(“string”);//报错,因为它不知自己示来匹配就一定是String
cols.size();//没错,此方法与类型参数没有关系。
//下面为什么可以?是相当于Collection<?> cols = new HashSet<Date>();?
//为什么不是相当于上面传入来的实参:
//Collection<Integer> arr = new HashSet<Date>();?或 Collection<Object> arr2 = new HashSet<Date>();?
cols = new HashSet<Date>();
}
}
|
|