Instantly teach you how to use the retainAll method of list in Java

Introduction to retainAll method

When we have two list sets, we can use the retainAll method to find the subsets of the two list sets. RetainAll is a method provided in the collection interface. Each implementation class has its own implementation method. Here we introduce the implementation method of ArrayList.

RetainAll source code depth

You can see the retainAll method in the collection interface. You need to pass in a collection.

boolean retainAll(Collection<?> c);

Enter the method implementation of ArrayList. You can see the following code:

    public boolean retainAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c,true);
    }

As can be seen from the above code, the incoming collection cannot be null. Next, look at the batchremove method.

    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) {
                // clear to let GC do its work
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }

We can see the flow of the above method as follows: first obtain all the elements of the current object, and then mark the number of common elements of the two sets through R and W variables. The initialization flag bit is false. Then enter the loop to traverse the current collection. If the incoming collection contains the element of the current collection, the element will be saved directly. Finally, in the finally block, if R is not equal to size, it proves that an exception occurred during the loop, then copy the remaining elements and recalculate the remaining element values of the array. If the remaining element values are not equal to size, the redundant positions are cleared. Change the value of modcount. This modcount is the value of the parent class abstartlist. The initial value is 0. If the content in the collection is not modified once, it will be increased by 1. Finally, reset the size. Returns whether to modify the value.

RetainAll returns a description of the value

Here are two instructions. First: Returns FALSE if the size of the array of set a has not changed. False is also returned if set a and set B are identical sets.

public static void main(String[] args) {
        ArrayList<String> list1= new ArrayList<String>();
        list1.add("123");
        ArrayList<String> list2= new ArrayList<String>();
        list2.add("123");
        System.out.println(list1.retainAll(list2)); 
    }

The above code will return false. Second: if two collections do not intersect, true will be returned.

public static void main(String[] args) {
        ArrayList<String> list1= new ArrayList<String>();
        list1.add("123");
        ArrayList<String> list2= new ArrayList<String>();
        list2.add("12345");
        System.out.println(list1.retainAll(list2));
    }

The above code will return true. Summary: when the size of set a changes, it returns true, and when the size does not change, it returns false.

Judgment method of retainAll

public static void main(String[] args) {
        ArrayList<String> list1= new ArrayList<String>();
        list1.add("123");
        ArrayList<String> list2= new ArrayList<String>();
        list2.add("123");
        list1.retainAll(list2);
        if(list1.size()>0){
            System.out.println("有交集");
        }else{
            System.out.println("没有交集");
        }
    }

Determine whether there is intersection by judging the size of the set. Cannot be judged by the true and false returned by the method.

The actual effect of retainAll is used

We declare two sets and reserve the intersection of the two sets by calling retainAll. Finally, look at the output effect.

    public static void main(String[] args) {
        Collection collection1 = new ArrayList();
        collection1.add("a");
        collection1.add("b");
        collection1.add("c");
        Collection collection2 = new ArrayList();
        collection2.add("ab");
        collection2.add("abc");
        collection2.add('a');
        System.out.println(collection1);
        boolean flag = collection1.retainAll(collection2);
        System.out.println(flag);
        System.out.println(collection1);
    }

The results are as follows:

[a,b,c]
true
[a]

The intersection of two combinations is preserved.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>