简体   繁体   中英

Compare two HashMaps keys for equality?

I have two HashMap<HashSet<String>, Long> that I want to compare based on the Key. The Key is a HashSet<String> , I might need to change to TreeSet<String> but I don't think it is necessary. How would I compare these?

NOTE: The Map is just used as a wrapper around a single Set.

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

I want to check the 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?

The equals() contract of Set says:

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. This ensures that the equals method works properly across different implementations of the Set interface.

So your code will work as long as the Set implementation follows the contract.

However, this may be dangerous depending on what your code does with the Sets that are used as keys. Once an object is used as a key in a Map, it shouldn't change because that breaks the contract of 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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