Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

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?

share|improve this question

5 Answers 5

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 IllegalArgumentException if the provided String does not exists.

share|improve this answer
    
Answer's reference website. Adding the link for full overview. –  bonCodigo Nov 17 '12 at 11:20

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":

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);
share|improve this answer
    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
   }
share|improve this answer

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.

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.

share|improve this answer
    
@jakub... yeah it would be good enough if you can post an example –  pratzy Nov 19 '12 at 18:35
    
@pratzy Example given –  Jakub Zaverka Nov 20 '12 at 22:33

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);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.