关于java

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());
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值