Java - Enum with array field
24,018
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)
Author by
Admin
Updated on October 31, 2020Comments
-
Admin over 3 years
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