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;
  }
}

Inheritance and polymorphism also apply to Enums

However an Enum cannot extend a class but it can implement an interface.



public interface AGLThing {
    public int id();
}


public enum GLBuffers implements AGLThing {

    VERTEX(0),
    ELEMENT(2);
    private final int id;

    private GLBuffers(final int id) {
        this.id = id;
    }

    @Override
    public int id() {
        return id;
    }

    @Override
    public String toString() {
        return this.name() + ",id: " + this.id();
    }
}




 public static void main(String[] args) {
        AGLThing vertexBufferInfo = GLBuffers.VERTEX;
        int vertexBufferId = vertexBufferInfo.id();
        System.out.println("Vertex Buffer id=" + vertexBufferId);
        System.out.println(vertexBufferInfo.toString());
    }

Output:

Vertex Buffer id=0
VERTEX,id: 0