0

I want to enumerate colors and use Color instances. Therefore I have created an enum with a private field and a get-function, but using it is cumbersome because of the need to call getColor().

Is there a better approach at directly using the enumeration constant without calling getColor()?

public class ColorListTest {
    public enum ColorList
    {
        WHITE(new Color(255, 255, 255)),
        BLACK(new Color(255, 255, 255)),
        ;

        private Color color;
        private ColorList(Color color) { this.color = color; }
        public Color getColor() { return color; }
    }

    public static void main(String[] args)
    {
        Color color = ColorList.WHITE.getColor();
        // I'd rather have something similar to:
        // Color color = WHITE;
        // Color color = ColorList.WHITE;
    }

}

The answer to Using enums as key for map question suggests to use a map, which also needs to call get().

Another option is to use a list of constants, which is less type safe since there is no enum anymore:

static public class ColorList
{
    static final Color WHITE = new Color(null, 255, 255, 255);
    static final Color BLACK = new Color(null, 0, 0, 0);
}

(The other posts I found seem to deal with string conversions a lot.)

So do you have a recommendation on a nice to use enum?

Community
  • 1
  • 1
Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137

2 Answers2

2

The only thing you can do which might be nicer is to use a static import.

import static mypackage.ColourList.*;

public static void main(String[] args) {
    Color color = WHITE.getColor();
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Use enumerators to define constants that you want to use. You can define the enumarator in a different class file and directly call the constants rather than defining it inside a class.

7dr3am7
  • 755
  • 1
  • 8
  • 21
  • I defined the constant within the class just to give a brief example. – Micha Wiedenmann Oct 02 '12 at 09:37
  • Ops, sorry! yes, I soon realized that you meant a nicer way. If you do use static imports, please create a class with a private constructor and define public static variables :) that would give a better flexibility: http://en.wikipedia.org/wiki/Constant_interface – 7dr3am7 Oct 02 '12 at 14:31