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]

相關文章
相關標籤/搜索