I have 2 different instances of HashMap
I want to merge the keysets of both HashMaps;
Code:
Set<String> mySet = hashMap1.keySet();
mySet.addAll(hashMap2.keySet());
Exception:
java.lang.UnsupportedOperationException
at java.util.AbstractCollection.add(AbstractCollection.java:238)
at java.util.AbstractCollection.addAll(AbstractCollection.java:322)
I don't get a compile warning or error.
From java doc this should work. Even if the added collection is also a set:
boolean addAll(Collection c)
Adds all of the elements in the specified collection to this set if
they're not already present (optional operation). If the specified
collection is also a set, the addAll operation effectively modifies
this set so that its value is the union of the two sets. The behavior
of this operation is undefined if the specified collection is modified
while the operation is in progress.
Best Answer
If you look at the docs of the
HashMap#keySet()
method, you'll get your answer(emphasis mine).Therefore, you need to create a new set and add all the elements to it, instead of adding the elements to the
Set
returned by thekeySet()
.