1

I'm using enums like below snippet and it is very helpful for me. However, when I want to define more than one ENUM (e.g. ENUM2, ENUM3), which have same parameters, I have to write everything that is tagged as "repeated code" in the snippet.

I'm thinking to encapsulate all parameters (p1, ...) within an object and just to give a reference to this object in the enum. However, this idea disturbs me since other extra instances will be generated.

Is the above approach is right, or how can solve this problem?

public enum ENUM1 {
    KEY_1(p1, p2, ..., pn),
    ...
    KEY_M(p1, p2, ..., pn);

    // constructor

    // REPEATED CODE
    private int p1, p2, ..., pn;
    public getP1();
    ...
    public getPM();
}
3
  • 1
    You could create an Enum containing the parameter set and getting passed to the second Enum - but then why having a second Enum at all? :-) Commented Aug 18, 2014 at 19:41
  • See stackoverflow.com/questions/1414755/… Commented Aug 18, 2014 at 19:43
  • @Smutje: enums with identical parameters can still be useful, otherwise why have parameter-less enums? Commented Aug 18, 2014 at 20:03

1 Answer 1

2

Try this:

public enum ENUM1 {

    KEY_1(Arrays.asList(1, 2, 3)),
    KEY_2(Arrays.asList(4, 5, 6));

    ENUM1(List<Integer> ps) {
        params = Collections.unmodifiableList(ps);
    }

    private List<Integer> params;

    public int getP(int idx) {
        return params.get(idx);
    }

}

Given that you have several parameters of the same type, you could use a collection. Later, when you need to retrieve a particular parameter use the getP() method, just remember that the indexes are 0-based.

Sign up to request clarification or add additional context in comments.

Comments

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.