錯誤的方式
public static void PRintCollection(Collection<Object> cols){ for(Object obj:cols){ System.out.println(obj); } /** cols.add("string");//沒錯 cols=new HashSet<Date>();//會報告錯誤! */}
正確的方式:
public static void printCollection(Collection<?> cols){ for(Object obj:cols){ System.out.println(obj); } /** cols.add("string");//錯誤,因為他不知道自己未來匹配就一定是Stirng cols.size();//沒錯,此方法與類型參數沒有關系 cols=new HashSet<Date>();//沒錯,可以和 Collection<?>畫等號 */} 上圖中,大紅叉的方法都是和類型相關的,在使用泛型通配符?時,不能調用。
Collection<?> a可以和任意參數化的類型匹配,但到底匹配的是什么類型,只有以后才知道,所以,
a=new ArrayList<Integer>();和 a= new ArrayList<String>();都可以,但a.add(new Date);或者 a.add("abc");都不行。
Cols<Object>中的Object只是說明Cols<Object>實例對象中的方法接收的參數是Object
Cols<Object>是一種具體類型,new HashSet<Date>也是一種具體類型,兩者沒有兼容性。
限定通配符的上邊界
正確 Vector<? extends Number> x=new Vector<Integer>();
錯誤 Vector<? extends Number> x=new Vector<String>();
限定通配符的下邊界
正確 Vector<? super Integer> x=new Vector<Number>();
錯誤 Vector<? super Integer> x=new Vector<Byte>();
提示
限定通配符總是包括自己
新聞熱點
疑難解答