Java ArrayList常用方法

Java ArrayList retainAll()方法  用于求两个arraylist的交集,并将交集存储在第一个arraylist中。

语法

语法如下:
boolean arraylist.retainAll(Collection<?> c)

参数

  • c: 要求交集的第二个集合

返回值

成功返回true,失败返回false

注意

对象相等的判断使用了arraylist的contains方法 ,所以对于对象的判断需要重写equals()方法。具体看下面的例2.

例子

介绍两个例子了解该函数的使用方法 

例1

字符串元素

import java.util.ArrayList;
import java.util.List;

public class ArrayListSubList {
    public static void main(String[] args) {
        List<String> arrayList1 = new ArrayList<String>();
        arrayList1.add("a");
        arrayList1.add("b");
        arrayList1.add("c");
        arrayList1.add("d");
        arrayList1.add("e");

        List<String> arrayList2 = new ArrayList<String>();
        arrayList2.add("a");
        arrayList2.add("c");
        arrayList2.add("f");
        arrayList2.add("g");

        boolean b = arrayList1.retainAll(arrayList2);
        System.out.println(b);
        System.out.println(arrayList1);

    }
} 

输出:

true
[a, c]

例2

对象元素

import java.util.ArrayList;
import java.util.List;

public class Test2 {
    public static void main(String[] args) {
        Employee e1 = new Employee("张三","male", 22);
        Employee e2 = new Employee("李四","male", 24);
        Employee e3 = new Employee("王五","male", 26);
        Employee e4 = new Employee("赵六","male", 28);
        Employee e5 = new Employee("王五","male", 26);
        //e3和e5的元素值相同 ,相同的比较使用的是arraylist的contains方法,需要重写类的equals方法才能判断相同,参考 https://www.yxjc123.com/post/1354

        List<Employee> arrayList1 = new ArrayList<Employee>();
        arrayList1.add(e1);
        arrayList1.add(e2);
        arrayList1.add(e3);

        List<Employee> arrayList2 = new ArrayList<Employee>();
        arrayList2.add(e4);
        arrayList2.add(e5);

        boolean b = arrayList1.retainAll(arrayList2);
        System.out.println(b);
        System.out.println(arrayList1);//返回e2和e3

    }
}


//JavaBean.java
class  Employee{

    private String name;
    private String sex;
    private Integer age;

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if(o == this)
            return true;
        if(!(o instanceof Employee))
            return false;
        if (o instanceof Employee) {
            Employee person = (Employee)o;
            return person.name.equals(name)
                    && person.sex.equals(sex)
                    && person.age.equals(age)
                    ;
        }
        return false;
    }

    public Employee(String name, String sex, Integer age) {
        this.name = name;
        this.sex = sex;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
} 

输出:

true
[Employee{name='王五', sex='male', age=26}]

内部实现

 /**
 * Retains only the elements in this list that are contained in the
 * specified collection.  In other words, removes from this list all
 * of its elements that are not contained in the specified collection.
 *
 * @param c collection containing elements to be retained in this list
 * @return {@code true} if this list changed as a result of the call
 * @throws ClassCastException if the class of an element of this list
 *         is incompatible with the specified collection
 * (<a href="Collection.html#optional-restrictions">optional</a>)
 * @throws NullPointerException if this list contains a null element and the
 *         specified collection does not permit null elements
 * (<a href="Collection.html#optional-restrictions">optional</a>),
 *         or if the specified collection is null
 * @see Collection#contains(Object)
 */
public boolean retainAll(Collection<?> c) {
    Objects.requireNonNull(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) {
            // 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;
} 
 我们看到相等的判断使用了arraylist的contains方法 ,所以对于对象的判断需要重写equals()方法。