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

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

boolean retainAll(Collection<?> c) ;this

//api中给的注释code

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

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

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

回true集合A发生改变源码

//jdk中实现的源码it

Boolean removeAll(Collection<?> c)io

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

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]

相关文章
相关标签/搜索