泛型的应用

6 泛型的应用

泛型类

6.1 ArrayList

    // 内部存储为数组
    transient Object[] elementData; 

    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }
    
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

    public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(size + numNew);  // Increments modCount
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;
    }

6.2 TypeHandler

用UT展示

通配符

6.3 CollectionUtils.containsAll()

    public static boolean containsAny(Collection<?> coll1, Collection<?> coll2) {
        Iterator i$;
        Object aColl1;
        if (coll1.size() < coll2.size()) {
            i$ = coll1.iterator();

            while(i$.hasNext()) {
                aColl1 = i$.next();
                if (coll2.contains(aColl1)) {
                    return true;
                }
            }
        } else {
            i$ = coll2.iterator();

            while(i$.hasNext()) {
                aColl1 = i$.next();
                if (coll1.contains(aColl1)) {
                    return true;
                }
            }
        }

        return false;
    }

Iterable

什么时候需要实现Iterable

你可能感兴趣的:(泛型的应用)