Stupid enum tricks

Number of elements


public enum Foo
{
  A,B,C;

  public static final int length = Foo.values().length;
}

As a singleton
Probably the easiest way to safely create a singleton in java if no parent is needed, but an enum can implement any number of interfaces:


public enum Foo
{
  INSTANCE;
  // instance methods here
}

Note that the enum instance is constructed on class load:


enum E {
    $;
    {
        System.out.println("Whoa! Hello World?!"); //this will in fact print when E.class is loaded (main() is run)
    }
    
    public static void main(String[] a) {}
}

As a static utility class


public enum Foo
{
  ;
  // static methods here
}

Tree relations
All kinds of stupid tricks you can do with this. Minimal example here just shows a boolean test of hierarchy membership.


public enum TreeEnum {
  THING,
    SUB_THING_1(THING),
    SUB_THING_2(THING),
      SUB_SUB_THING_2(SUB_THING_2),
  OTHER,
    SOME_OTHER(OTHER),
    AND_YET_ANOTHER(OTHER)
  ;
  
  private final TreeEnum parent;
  private final int      depth;
  
  private TreeEnum() { this(null);}
  
  private TreeEnum(TreeEnum parent)
  {
    this.parent = parent;
    
    if (parent != null) {
      this.depth  = parent.depth+1;
    } else {
      this.depth  = 0;
    }
  }
  
  public boolean isA(TreeEnum other)
  { 
    TreeEnum t = this;
    
    do {
      if (t == other) return true;
      t = t.parent;
    } while(t != null);
    
    return false;
  }
}