Collection中的之retainAll()方法的理解

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

//在jdkapi中的方法,说明返回值为boolean类型,

boolean retainAll(Collection c) ;

//api中给的注释

//Retains only the elements in this list that are contained in the specified collection

//只保留在此集合中存在的元素,

//A.retainAll(B),A调用这个方法之后,集合A中只剩下存在于B中的元素,返回值为false表示集合A没改变,返

回true集合A发生改变

//jdk中实现的源码

Boolean removeAll(Collection c)

public boolean retainAll(Collection c) { //返回值是否发生改变

    return batchRemove(c, true);

}

private boolean batchRemove(Collection c, boolean complement) {

    final Object[] elementData = this.elementData;

    int r = 0, w = 0;

    boolean modified = false;

    try {

        for (; r < size; r++)

            if (c.contains(elementData[r]) == complement)
                elementData[w++] = elementData[r];
    } finally {
        // Preserve behavioral compatibility with AbstractCollection,
        // even if c.contains() throws.
        if (r != size) {
            System.arraycopy(elementData, r,
                             elementData, w,
                             size - r);
            w += size - r;
        }
        if (w != size) {
            for (int i = w; i < size; i++)
                elementData[i] = null;
            modCount += size - w;
            size = w;
            modified = true;
        }
    }
    return modified;
}

example:

public class collection_test {

public static void main(String args[]) {

Collection c=new ArrayList();

Collection c1=new ArrayList(); c.add("a1"); c.add("a2");

c1.add("a3"); c1.add("a1"); c1.add("a2");

System.out.println(c.retainAll(c1)); System.out.println(c.toString()); System.out.println(c1.toString());

} }

结果: false [a1, a2] [a3, a1, a2]

转载于:https://my.oschina.net/u/2511906/blog/3002440

你可能感兴趣的:(Collection中的之retainAll()方法的理解)