开发者

Adding enum type to a list

If I need to add an enum attribute to a list, how do I declare the list? Let us say the enum class is:

public enum Country{ USA, CANADA; }

I want to do:

List<String> l = new ArrayList<>();
l.add(Country.USA);开发者_运维问答

What needs to be used instead of List<String>?


Should be:

List<Country> l = new ArrayList<Country>();
l.add(Country.USA); // That one's for you Code Monkey :)


If you want the string type use this:

l.add(Country.USA.name());

otherwise the answer of MByD


If you want to hold any enum, use this:

List<? extends Enum<?>> list = new ArrayList<Country>();
Enum<?> someEnumValue = list.get(0); // Elements can be assigned to Enum<?>
System.out.println(someEnumValue.name()); // You can now access enum methods
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜