I’m trying to migrate my Oracle JDK 11 application to JDK 17.0.7, when I tried to access add() in java.utils.Set, It throws
java.lang.UnsupportedOperationException
I checked with Stackoverflow and found, java.util.Set’s implementation is not fully support add() function yet, it was marked as optional.
My question is, Which java vendor’s Java 17 it already supported or implemented java Set add() methods?
I have quite a lot Java objects need this function in my application.
If anyone have idea, Please advise.
It does not depend on the vendor but on the particular class implementing the Set
interface: some sets are unmodifiable, so you cannot add anything to them. The Javadoc specifies any usage limitation for each implementing class. For example a Set
returned by Collections.unmodifiableSet()
is, obviously, unmodifiable.
Perhaps during the upgrade of Java you have also upgraded some dependency and the new version of that dependency returns an unmodifiable Set
. Check the Javadoc of the method that returns that Set
.
You’ll probably have to modify your code and copy the content of that Set
in a new modifiable instance, for example:
Set newSet = new HashSet(oldSet);
Of course you should also use generics.
I’m afraid you’re asking the wrong question, as there is most likely no (or very little) difference between vendors in this case. The real question that you should be following up is which implementation of
java.util.Set
are you using? The “classic”java.util.HashSet
for example clearly supportsadd
, but someSet
implementation returned as a view onto some other data structure might not. What doesyourSet.getClass()
return?Yeah, I am using HashSet to create the Set Instance.
you better include a minimal reproducible example in the question, otherwise we will need to guess most of it (the stack trace should also hint what class is being used )
Show us your code. There is no possibility that calling
add
on a HashSet is producing that exception. However, if your code doesHashSet.of(element)
, that is actually callingSet.of(element)
which produces an unmodifiable Set.