在其上使用了retainAll方法之后,如何重设HashSet?

时间:2019-01-29 07:40:28

标签: java hashset

我有三个HashSet,它们的访问者来自不同的国家。如果我使用Mexico.retainAll(Cuba);然后Mexico.retainAll(牙买加)它给了我访问过所有三个国家的所有人员的列表。哪个是: 奥利维亚,约翰,威廉

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

设置值如下:

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

[Olivia,Zoe,Jennifer,Susan,John,Isabella,William,Jack,Emma和Sophia]

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

[Olivia,Tom,Jennifer,Susan,John,William,Jack,Emma,Ava,Sophia,Lily]

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

[Olivia,Tom,John,William,Ava,Jessica,Lily]

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],但我的设置空了。

1 个答案:

答案 0 :(得分:4)

Mexico.retainAllMexico Set进行了突变,因此您无法依次呼叫allThreeCountriesonlyMexicoCuba,并期望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());
    }
}