javaenumsguava

ImmutableSet from Guava or Java enum


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!


Solution

  • 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));