您的位置:首页 > 编程语言 > Java开发

关于java

2016-04-06 17:35 555 查看
1,生产者使用extends , List <extends T> , 因此你不能往列表里添加任何元素

2,消费者使用super, List <super T> , 因此你不能保证从中读取到的元素的类型

3,既是生产者又是消费者,不能用

例子:JDK 1.8 java.util.Collections里的copy方法

/**
* Copies the elements from the source list to the destination list. At the
* end both lists will have the same objects at the same index. If the
* destination array is larger than the source list, the elements in the
* destination list with {@code index >= source.size()} will be unchanged.
*
* @param destination
*            the list whose elements are set from the source list.
* @param source
*            the list with the elements to be copied into the destination.
* @throws IndexOutOfBoundsException
*             when the destination list is smaller than the source list.
* @throws UnsupportedOperationException
*             when replacing an element in the destination list is not
*             supported.
*/
public static <T> void copy(List<? super T> destination, List<? extends T> source) {
if (destination.size() < source.size()) {
throw new IndexOutOfBoundsException("destination.size() < source.size(): " +
destination.size() + " < " + source.size());
}
Iterator<? extends T> srcIt = source.iterator();
ListIterator<? super T> destIt = destination.listIterator();
while (srcIt.hasNext()) {
try {
destIt.next();
} catch (NoSuchElementException e) {
// TODO: AssertionError?
throw new IndexOutOfBoundsException("Source size " + source.size() +
" does not fit into destination");
}
destIt.set(srcIt.next());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: