简体   繁体   English

Java - 包含数组字段的枚举

[英]Java - Enum with array field

I want to store a list names and individual nicknames for each name as an Enum in Java. 我想将每个名称的列表名称和单个昵称存储为Java中的Enum。 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? 我不喜欢不得不重复new String[] {...} ,所以我想知道是否有人可以建议一种替代的,更简洁的实现方法?

Cheers, 干杯,

Pete 皮特

Vararg parameters: Vararg参数:

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) 详细信息 (请参阅“任意数量的参数”部分)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM