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?

2
  • 2
    Why do you use an enum ? If the defined values aren't the complete list of possible values, but just some convenient values, use constants, not an enum. Commented Oct 2, 2012 at 8:03
  • That is a good point, and I have not thought about it. Commented Oct 2, 2012 at 9:39

2 Answers 2

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();
}
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

I defined the constant within the class just to give a brief example.
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: en.wikipedia.org/wiki/Constant_interface

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.