Reputation: 149
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?
Upvotes: 0
Views: 3671
Reputation: 31648
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);
Upvotes: 1