Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Java's EnumSet mutable?

Tags:

java

Is there any way to modify an EnumSet object? It seems that (for example) EnumSet.add is inherited from AbstractSet and that throws an UnsupportedOperationException.

Yet it looks as if EnumSet is modifiable; otherwise why bother having a clone() method, and why would Guava have Sets.immutableEnumSet()? Is there a method of EnumSet that's escaped my mind?

like image 928
DodgyCodeException Avatar asked Dec 08 '22 15:12

DodgyCodeException


2 Answers

Yes EnumSet is modifiable. If you want to create an immutable EnumSet then go for immutableEnumSet.

  • Returns an immutable set instance containing the given enum elements. Internally, the returned set will be backed by an EnumSet.
  • The iteration order of the returned set follows the enum's iteration order, not the order in which the elements appear in the given collection.

Parameters: elements - the elements, all of the same enum type, that the set should contain

Returns: an immutable set containing those elements, minus duplicates

like image 68
Subash J Avatar answered Jan 03 '23 10:01

Subash J


EnumSet is just an abstract class. It's implementation overrides add method which makes it mutable and hence the below is possible

EnumSet<MyEnum> enumSet = EnumSet.of(MyEnum.A);
enumSet.add(MyEnum.B);


private static enum MyEnum {
   A,B,C;
}
like image 35
user7 Avatar answered Jan 03 '23 11:01

user7