Java - 带有数组字段的枚举

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4059702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:06:24  来源:igfitidea点击:

Java - Enum with array field

javaarraysrefactoringenumsconstants

提问by

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:

我想将每个名称的列表名称和个人昵称存储为 Java 中的 Enum。昵称的数量不会改变。目的是能够从昵称中获得全名。目前我已经实现了这样的:

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

皮特

采纳答案by Nikita Rybak

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)

详细信息(参见“任意数量的参数”部分)