本文介绍了Java - 枚举与数组字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将每个名称的列表名称和个别昵称作为Java中的枚举存储。昵称的数量不会改变。目的是能够从昵称中获取一个全名。目前我已经实现了这样:
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
}
}
$ b $我非常不喜欢重复 new String [] {...}
,所以我想知道是否有人可以建议一个替代,更简洁的方法来实现这个?
I quite dislike having to repeat new String[] {...}
, so I wondered if anyone could suggest an alternative, more concise, method of implementing this?
干杯,
Pete
推荐答案
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)
这篇关于Java - 枚举与数组字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!