简体   繁体   English

比较两个HashMaps键是否相等?

[英]Compare two HashMaps keys for equality?

I have two HashMap<HashSet<String>, Long> that I want to compare based on the Key. 我有两个要基于Key比较的HashMap<HashSet<String>, Long> The Key is a HashSet<String> , I might need to change to TreeSet<String> but I don't think it is necessary. 关键是HashSet<String> ,我可能需要更改为TreeSet<String>但我认为没有必要。 How would I compare these? 我将如何比较这些?

NOTE: The Map is just used as a wrapper around a single Set. 注意:映射仅用作单个Set的包装。

for(HashMap<HashSet<String>, Long> entry : ListOfMaps) {
    if(entry.keySet().equals(entry2.keySet())) {
        // do something
    }
}

I want to check the Set1.equals(Set2). 我想检查Set1.equals(Set2)。

The set must be exactly the same. 集合必须完全相同。 Since there is only one Set<String> in each HashMap<Set<String>, Long> it makes me nervous that I am grabbing all the Keys, or is this okay? 由于每个HashMap<Set<String>, Long>只有一个Set<String> HashMap<Set<String>, Long>让我感到紧张,因为我要抓住所有Key,还是可以吗?

The equals() contract of Set says: Set的equals()合约说:

Returns true if the given object is also a set, the two sets have the same size, and every member of the given set is contained in this set. 如果给定对象也是一个集合,两个集合的大小相同,并且给定集合的每个成员都包含在此集合中,则返回true。 This ensures that the equals method works properly across different implementations of the Set interface. 这样可确保equals方法可在Set接口的不同实现中正常工作。

So your code will work as long as the Set implementation follows the contract. 因此,只要Set实现遵循合同,您的代码就会起作用。

However, this may be dangerous depending on what your code does with the Sets that are used as keys. 但是,这可能很危险,具体取决于您的代码对用作键的Set所做的操作。 Once an object is used as a key in a Map, it shouldn't change because that breaks the contract of Map. 一旦将对象用作Map中的键,就不应更改它,因为这会破坏Map的契约。

Map<Set<String>, T> map = HashMap<>();
Set<String> mySet = new HashSet<>();

mySet.add("first");
map.put(mySet, myValue);


Set<String> copyOfMySet = new HashSet<>(mySet);

//returns true
map.contains(copyOfMySet);

//modifying mySet
mySet.remove("first");

//this will now return false
map.contains(copyOfMySet);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM