【java】集合操作中的retainAll的坑


 

JDK1.8

首先,set1中有值, set2中無值

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Sets;
import java.util.*;



public class ListTest {

    public static void main(String[] args) throws Exception {

        Set<Long> set1 = new HashSet<>();
        set1.add(1L);
        set1.add(2L);

        Set<Long> set2 = new HashSet<>();


        Sets.SetView<Long> intersection = Sets.intersection(set1, set2);
        System.out.println(JSON.toJSONString(intersection));

        System.out.println(JSON.toJSONString(set1));
        System.out.println(JSON.toJSONString(set2));


        set1.retainAll(set2);
        System.out.println(JSON.toJSONString(set1));
        System.out.println(JSON.toJSONString(set2));

    }
}

結果:

 

 

 

 

再來一次,set2中放值

public static void main(String[] args) throws Exception {

        Set<Long> set1 = new HashSet<>();
        set1.add(1L);
        set1.add(2L);

        Set<Long> set2 = new HashSet<>();
        set2.add(1L);

        Sets.SetView<Long> intersection = Sets.intersection(set1, set2);
        System.out.println(JSON.toJSONString(intersection));

        System.out.println(JSON.toJSONString(set1));
        System.out.println(JSON.toJSONString(set2));


        set1.retainAll(set2);
        System.out.println(JSON.toJSONString(set1));
        System.out.println(JSON.toJSONString(set2));

    }

結果如下

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM