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());
                }
            }
        }
    
  • 相关阅读:
    FFMPEG音视频基础问题和被面试问到的东西
    OpenGL学习
    FFMPEG起航之旅
    SurfaceView、TextureView对比和学习
    对文件拷贝、删除操作、对时间的计算以及转化
    音视频开发
    企业级Android应用架构设计与开发
    屏幕分辨率的适配&&开发文档的介绍
    设计模式的学习
    自定义Dialog的模版
  • 原文地址:https://www.cnblogs.com/suxuan/p/4970467.html
Copyright © 2011-2022 走看看