I read here a nice example about using ImmutableSet from Guava. The example is reported here for the sake of completeness:
public static final ImmutableSet<String> COLOR_NAMES = ImmutableSet.of(
  "red",
  "orange",
  "yellow",
  "green",
  "blue",
  "purple");
class Foo {
  Set<Bar> bars;
  Foo(Set<Bar> bars) {
    this.bars = ImmutableSet.copyOf(bars); // defensive copy!
  }
}
The question is, can I obtain the same result by using a Java enum?
PS: This question added into my mind more chaos!
Can I obtain the same result by using a Java enum?
Yes, you can. Did you try it?
FYI, there's also specialized version of ImmutableSet which holds enum's constants - Sets.immutableEnumSet (internally it uses EnumSet).
Some examples (paraphrasing Wiki examples):
public class Test {
  enum Color {
    RED, ORANGE, YELLOW, GREEN, BLUE, PURPLE;
  }
  static class Baz {
    ImmutableSet<Color> colors;
    Baz(Set<Color> colors) {
      this.colors = Sets.immutableEnumSet(colors); // preserves enum constants 
                                                   // order, not insertion order!
    }
  }
  public static void main(String[] args) {
    ImmutableSet<Color> colorsInInsertionOrder = ImmutableSet.of(
        Color.GREEN, Color.YELLOW, Color.RED);
    System.out.println(colorsInInsertionOrder); // [GREEN, YELLOW, RED]
    Baz baz = new Baz(colorsInInsertionOrder);
    System.out.println(baz.colors); // [RED, YELLOW, GREEN]
  }
}
EDIT (after OP's comment):
Do you want all enum constants in ImmutableSet? Just do:
Sets.immutableEnumSet(EnumSet.allOf(Color.class));
                        No, not quite. Compare
public enum Color {
    RED, ORANGE, YELLOW, GREEN, BLUE, PURPLE;
}
Set<Color> colors = EnumSet.allOf(Color.class);
with
Set<String> colors = ImmutableSet.of(
  "red", "orange", "yellow", "green", "blue", "purple"
);
Since Java is statically typed, you will have a Set<Color> in the first example, and a Set<String> in the latter example.
Edit 1
Another difference is that you can create ImmutableSet of arbitrary size in runtime (provided that no single element equals() any of the other elements). In contrast, an EnumSet can also be created during runtime, but it can never contain more elements than the number of enum values.
Edit 2
An ImmutableSet may contain elements of different classes, as long as they implement the same interface. An EnumSet can only contain the enum type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With