Java泛型:通配符
因此,我正在阅读泛型,以便重新熟悉这些概念,特别是在涉及通配符的情况下,因为我几乎没有使用它们或碰到它们.从我所做的阅读中我无法理解为什么他们使用通配符.我不断遇到的一个例子如下.
void printCollection( Collection<?> c ) { for (Object o : c){ System.out.println(o); } } 为什么你不写这个: <T> void printCollection( Collection<T> c ) { for(T o : c) { System.out.println(o); } } 来自oracle网站的另一个例子: public static double sumOfList(List<? extends Number> list) { double s = 0.0; for (Number n : list) s += n.doubleValue(); return s; } 为什么这不是写的 public static <T extends Number> double sumOfList(List<T> list) { double s = 0.0; for (Number n : list) s += n.doubleValue(); return s; } 我错过了什么吗? 解决方法
从
Oracle开始:
interface Collection<E> { public boolean containsAll(Collection<?> c); public boolean addAll(Collection<? extends E> c); }
interface Collection<E> { public <T> boolean containsAll(Collection<T> c); public <T extends E> boolean addAll(Collection<T> c); // Hey,type variables can have bounds too! }
所以对于第一个例子来说,这是因为操作不依赖于类型. 对于第二个,这是因为它只取决于Number类. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |