java java中如何将字符串数组转换为枚举数组

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

How to convert string array to enum array in java

javaenumsarrays

提问by pratzy

I have a string array that contains the enum values taken from the user. How do I now convert this string array to enum array so that the elements can then be iterated and used further in other methods? This needs to be done in Java.

我有一个字符串数组,其中包含从用户那里获取的枚举值。我现在如何将此字符串数组转换为枚举数组,以便元素可以被迭代并在其他方法中进一步使用?这需要在 Java 中完成。

Basically I am asking is that for example if I have this array

基本上我要问的是,例如,如果我有这个数组

String [] names = {"Autumn", "Spring", "Autumn", "Autumn" };

and I have this enum

我有这个枚举

enum Season
{ 
    Autumn, Spring;
}

How do I now convert the above array of String type to an array of enum Season type?

我现在如何将上述 String 类型数组转换为 enum Season 类型数组?

回答by DaBlick

Here's a complete code example:

这是一个完整的代码示例:

private static List<Season> foo(List<String> slist) {
    List<Role> list = new ArrayList<>();
    for (String val : slist) {
        list.add(Season.valueOf(val));
    }
    return list;
}

Now if you want to make a generic method that would do this for any Enum, it gets a bit tricker. You have to use a "generic method":

现在,如果您想为任何 Enum 创建一个通用方法,它会变得有点棘手。您必须使用“通用方法”:

private static <T extends Enum<T>> List<T> makeIt(Class<T> clazz, List<String> values) {
    List<T> list = new ArrayList<>();
    for (String level : values) {
        list.add(Enum.valueOf(clazz, level));
    }
    return list;
}

You'd have to call this as follows:

你必须这样称呼它:

List<Strings> slist = ....
List<Season> elist= makeIt(Season.class, slist);

回答by Frank

Like this: code from here

像这样:来自这里的代码

public enum Weekdays {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

If you need to do a lookup you can do:

如果您需要进行查找,您可以执行以下操作:

Weekdays weekday = Weekdays.valueOf("Monday");
System.out.println(weekday);

But be carefull as this will throw an IllegalArgumentExceptionif the provided Stringdoes not exists.

但要小心,因为IllegalArgumentException如果所提供的String不存在,这将抛出一个。

回答by pstanton

to answer the actual question:

回答实际问题:

public <T extends Enum<T>> T[] toEnums(String[] arr, Class<T> type)
{
    T[] result = (T[]) Array.newInstance(type, arr.length);
    for (int i = 0; i < arr.length; i++)
        result[i] = Enum.valueOf(type, arr[i]);
    return result;
}

Season[] seasons = toEnums(names, Season.class);

回答by Jakub Zaverka

If you are using Swing and not command prompt or web form, you can actually pass enum instances into a JComboBox. When the user makes a selection, you will get the Enum instance directly, without having to translate between String and Enum. This has the advantage that you don't need to worry about changing Enum names or upper/lower case errors.

如果您使用的是 Swing 而不是命令提示符或 Web 表单,您实际上可以将枚举实例传递到 JComboBox。当用户进行选择时,您将直接获得 Enum 实例,而无需在 String 和 Enum 之间进行转换。这样做的好处是您无需担心更改 Enum 名称或大写/小写错误。

Example:

例子:

public class Enums 
{
    public enum Days{
        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; 

        public String toString() {
            //return user-friendly name, or whatever else you want.
                    //for complex rendering, you need to use cell renderer for the combo box
            return name().substring(0,1) + name().toLowerCase().substring(1, name().length());
        };
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Enum test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JComboBox<Days> combo = new JComboBox<>(Days.values());
        combo.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange() == ItemEvent.SELECTED){
                    Days selected = combo.getItemAt(combo.getSelectedIndex());
                    System.out.println(selected);
                }
            }
        });
        frame.add(combo);

        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

No type casting, no string matching. Super-safe.

没有类型转换,没有字符串匹配。超级安全。

回答by sunleo

    String s[]=new String[Numbers.values().length];
    int i =0;
    for (Numbers op : Numbers.values()) {
        s[i++] =op.toString();
        System.out.println(op.toString());
    }


   public enum Numbers {
    one,
    two,
    three
   }