Java Collection Add addAll(Collection coll1, Collection coll2)

Here you can find the source of addAll(Collection coll1, Collection coll2)

Description

A potentially more efficient addAll() for unordered Collections.

License

Open Source License

Parameter

Parameter Description
coll1 a parameter
coll2 a parameter

Return

the longer of the two collections after adding the shorter to the longer.

Declaration

public static <T, C extends Collection<T>> C addAll(Collection<T> coll1, Collection<T> coll2) 

Method Source Code

//package com.java2s;

import java.util.ArrayList;

import java.util.Collection;

public class Main {
    /**/*from  w  w w . j  av  a2s.co m*/
     * A potentially more efficient addAll() for unordered Collections.
     * @param coll1
     * @param coll2
     * @return the longer of the two collections after adding the shorter to the longer.  
     */
    public static <T, C extends Collection<T>> C addAll(Collection<T> coll1, Collection<T> coll2) {
        if (coll1 == null)
            return (C) coll2;
        if (coll2 == null)
            return (C) coll1;

        Collection<T> cSmaller, cBigger;
        if (coll1.size() < coll2.size()) {
            cSmaller = coll1;
            cBigger = coll2;
        } else {
            cSmaller = coll2;
            cBigger = coll1;
        }
        try {
            cBigger.addAll(cSmaller);
            return (C) cBigger;
        } catch (UnsupportedOperationException e) {
        }
        try {
            cSmaller.addAll(cBigger);
            return (C) cSmaller;
        } catch (UnsupportedOperationException e) {
        }
        ArrayList<T> newList = new ArrayList<T>(cBigger);
        newList.addAll(cSmaller);
        return (C) newList;
    }
}

Related

  1. addAll(Collection pCollection, Iterator pIterator)
  2. addAll(Collection integerCollection, int[] intArray)
  3. addAll(Collection c, T[] a)
  4. addAll(Collection col, T[] arr)
  5. addAll(Collection coll, T... elems)
  6. addAll(Collection collection, Collection toAdd)
  7. addAll(Collection collection, Iterable items)
  8. addAll(Collection collection, T... array)
  9. addAll(Collection collection, T... elementsToAdd)