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();
}
Ricardo Cristian Ramirez
  • 1,194
  • 3
  • 20
  • 42
  • 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? :-) – Smutje Aug 18 '14 at 19:41
  • See http://stackoverflow.com/questions/1414755/can-enums-be-subclassed-to-add-new-elements –  Aug 18 '14 at 19:43
  • @Smutje: enums with identical parameters can still be useful, otherwise why have parameter-less enums? – Sean Van Gorder Aug 18 '14 at 20:03

1 Answers1

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.

Óscar López
  • 232,561
  • 37
  • 312
  • 386