zoukankan      html  css  js  c++  java
  • Java 泛型中的PECS原则

    在泛型编程时,使用部分限定的形参时,<? super T>和<? extends T>的使用场景容易混淆,PECS原则可以帮助我们很好记住它们:

    生产者(Producer)使用extends,消费者(Consumer)使用super。

    留下一段代码加深印象(来自JDK 8 Collections.copy()源码)

    /**
         * Copies all of the elements from one list into another.  After the
         * operation, the index of each copied element in the destination list
         * will be identical to its index in the source list.  The destination
         * list must be at least as long as the source list.  If it is longer, the
         * remaining elements in the destination list are unaffected. <p>
         *
         * This method runs in linear time.
         *
         * @param  <T> the class of the objects in the lists
         * @param  dest The destination list.
         * @param  src The source list.
         * @throws IndexOutOfBoundsException if the destination list is too small
         *         to contain the entire source List.
         * @throws UnsupportedOperationException if the destination list's
         *         list-iterator does not support the <tt>set</tt> operation.
         */
        public static <T> void copy(List<? super T> dest, List<? extends T> src) {
            int srcSize = src.size();
            if (srcSize > dest.size())
                throw new IndexOutOfBoundsException("Source does not fit in dest");
    
            if (srcSize < COPY_THRESHOLD ||
                (src instanceof RandomAccess && dest instanceof RandomAccess)) {
                for (int i=0; i<srcSize; i++)
                    dest.set(i, src.get(i));
            } else {
                ListIterator<? super T> di=dest.listIterator();
                ListIterator<? extends T> si=src.listIterator();
                for (int i=0; i<srcSize; i++) {
                    di.next();
                    di.set(si.next());
                }
            }
        }
    
  • 相关阅读:
    【Idea】设置springboot启动环境
    python base64加密解密
    binascii.Error: Incorrect padding
    DataFrame随机采样
    检测和过滤异常值
    离散化和面元划分
    AttributeError: 'Categorical' object has no attribute 'levels'
    AttributeError: 'Categorical' object has no attribute 'labels'
    重命名轴索引
    替换值replace
  • 原文地址:https://www.cnblogs.com/suxuan/p/4970467.html
Copyright © 2011-2022 走看看