Java的:如何地图键集比较集? [重复]

问题描述 投票:-3回答:2

这个问题已经在这里有一个答案:

我有一个Map(称为masterMap)和一组。

masterMap包含这些价值观 - {1537=OK, 1538=OK, 1539=OK, 4003=OK}

Set selectedSet =new HashSet();
selectedSet.add(Integer.parseInt("4003"));
boolean compareMapAndSet=masterMap.keySet().equals(selectedSet);

但是,即使4003存在于地图上,compareMapAndSet总是false

什么是错的比较呢?

java dictionary set hashset
2个回答
3
投票

equals比较对象是否相等。它不检查第二组是第一的一个子集。为了获得该功能,您应该使用containsAll

boolean compareMapAndSet=masterMap.keySet().containsAll(selectedSet);

0
投票

从集 public boolean equals(Object o)

指定的对象与此set的相等性。返回trueif给定对象也是一组,这两组具有相同的大小,以及给定的所有成员都包含在这个集合。这确保了equals方法在Set接口的不同实现正常工作。 此实现首先检查指定的对象是这样的组;如果是这样,则返回true。然后,它检查指定对象是一组,其大小是相同的该组的大小;如果不是,则返回false。如果是这样,则返回containsAll((集合)O)。

注:但在你给出的例子您selectedSet没有相同的元素。

我想你想检查是否在selectedSet集合中的所有元素是masterMap.keySet()的一部分

对于没有滞留API,你必须遍历您设置selectedSet,如果它存在,检查它masterMap.keySet()。像下面的代码:

boolean compareMapAndSet = checkSubSet(masterMap.keySet(), selectedSet);
private static boolean checkSubSet(Set<Integer> keySet, Set<Integer> selectedSet) {
    for (Integer integer : selectedSet) {
        if (!keySet.contains(integer)) {
            return false;
        }
    }
    return true;
}

看到输出result

© www.soinside.com 2019 - 2024. All rights reserved.