java 将枚举类型添加到列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6969841/
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-10-30 18:05:19  来源:igfitidea点击:

Adding enum type to a list

javaenums

提问by Victor

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>?

需要用什么代替 List<String>?

回答by MByD

Should be:

应该:

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

回答by timaschew

If you want the string type use this:

如果你想要字符串类型使用这个:

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

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

otherwise the answer of MByD

否则MByD的答案

回答by Bohemian

If you want to hold anyenum, 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