16

I want to store a list names and individual nicknames for each name as an Enum in Java. The number of nicknames will not vary. The purpose is to be able to get a full name from a nickname. Currently I have implemented this like so:

public enum Names {

    ELIZABETH(new String[] {"Liz","Bet"}),    
    ...
    ;

    private String[] nicknames;

    private Names(String[] nicknames)
    {
        this.nicknames = nicknames
    }


    public Names getNameFromNickname(String nickname) {
       //Obvious how this works
    }
}

I quite dislike having to repeat new String[] {...}, so I wondered if anyone could suggest an alternative, more concise, method of implementing this?

Cheers,

Pete

1 Answer 1

38

Vararg parameters:

private Names(String... nicknames) {

Now you can invoke constructor without explicitly creating array:

ELIZABETH("Liz", "Bet", "another name")

Details (see "Arbitrary Number of Arguments" section)

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.