java Collection 中 containsAll 与 retainAll 的区别

卫诚
2023-12-01

/**
     * containsAll:集合collection1是否包含集合collection2
     * retainAll:求集合collection1与集合collection2的交集,会改变集合collection1的元素,其布尔值看集合collection1的元素是否减少,不变则是false
     * @param args
     */
    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("a");
        collection2.add("b");
//        collection2.add("d");
//        collection2.add("e");
        collection2.add("c");
        System.out.println(collection1);
        boolean flag = collection1.retainAll(collection2);
        System.out.println(flag);
        System.out.println(collection1);
        boolean flag1 = collection1.containsAll(collection2);
        System.out.println(flag1);
        System.out.println(collection1);

    }
 类似资料: