我有三个HashSet,分别由不同的人访问过不同的国家。如果我使用Mexico.retainAll(Cuba);然后是Mexico.retainAll(牙买加),它给我列出了访问这三个国家的所有人员的名单。哪个是:
奥利维亚·约翰·威廉

但是后来当我做Mexico.retainAll(Cuba);然后是Mexico.removeAll(Jamaica),以仅吸引访问过墨西哥和古巴而不是牙买加的人。它给我一个空的集吗?

设置值如下:

HashSet<String> Mexico = new HashSet<String>();

[奥利维亚,佐伊,詹妮弗,苏珊,约翰,伊莎贝拉,威廉,杰克,艾玛,索菲娅]
HashSet<String> Cuba = new HashSet<String>();

[Olivia,Tom,Jennifer,Susan,John,William,Jack,Emma,Ava,Sophia,Lily]
HashSet<String> Jamaica = new HashSet<String>();

[奥利维亚,汤姆,约翰,威廉,艾娃,杰西卡,莉莉]
public static void main(String[] args) throws FileNotFoundException {
    visitorPatternNOOP.allThreeCountries();
    visitorPatternNOOP.onlyMexicoCuba();
}


public class VisitorPatternNOOP {
    public void allThreeCountries (){
        Mexico.retainAll(Cuba);
        Mexico.retainAll(Jamaica);
        Iterator<String>  iterator = Mexico.iterator();
        System.out.println("These people has visited all three countries:  ");
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

    public  void onlyMexicoCuba (){
        Mexico.retainAll(Cuba);
        Mexico.removeAll(Jamaica);
        Iterator<String> iterator = Mexico.iterator();
        System.out.println("These people have visited Mexico and Cuba Only: ");
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}

输出应该是[Jennifer,Susan,Jack,Emma和Sophia],但我的设置空了。

最佳答案

Mexico.retainAll会使Mexico突变Set,因此您不能先调用allThreeCountries后跟onlyMexicoCuba,并且期望onlyMexicoCuba将看到Mexico集的原始内容。

您应该生成Mexico的副本Set,并对该副本进行突变。

public void allThreeCountries (){
    HashSet<String> result = new HashSet<>(Mexico);
    result.retainAll(Cuba);
    result.retainAll(Jamaica);
    Iterator<String> iterator = result.iterator();
    System.out.println("These people has visited all three countries:  ");
    while (iterator.hasNext()){
        System.out.println(iterator.next());
    }
}

public  void onlyMexicoCuba (){
    HashSet<String> result = new HashSet<>(Mexico);
    result.retainAll(Cuba);
    result.removeAll(Jamaica);
    Iterator<String> iterator = result.iterator();
    System.out.println("These people have visited Mexico and Cuba Only: ");
    while (iterator.hasNext()){
        System.out.println(iterator.next());
    }
}

关于java - 在上面使用了retainAll方法后,如何重置HashSet?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54416037/

10-09 19:54