1

given the following code...

private enum EventTypes {
    WORK, BREAK, WAIT, CLOSE, COMPLETE
}

public static void main(String[] args) {
    System.out.println("BREAK : " + EventTypes.BREAK);
    System.out.println(Arrays.asList(EventTypes.values()).contains("WORK"));
    System.out.println(Arrays.asList(EventTypes.values()).contains("WOR"));

}

This produces the output...

BREAK : BREAK
false
false

Now, from the output I can see "BREAK" exists as a String - so why does it believe "WORK" does not exist in the above enum?

4 Answers 4

3

Enum values aren't strings. Do this :

Arrays.asList(EventTypes.values()).contains(EventTypes.WORK));

If you want to know if your string is the name of an enum value, do

boolean exist = false;
try {
    EventTypes.valueOf("WORK");
    exist = true; 
} catch (IllegalArgumentException e) {}
0
2

You can remove the quotes but if you cannot you can parse the String.

Arrays.asList(EventTypes.values()).contains(EventTypes.valueOf("WORK"))

A brittle, but simple approach is to compare the strings

Arrays.toString(EventTypes.values()).contains("WORK")

The later may be ok for unit tests but not suitable for production code.

1
  • 1
    Could you please explain why the second method is that dangerous? Commented Oct 11, 2012 at 10:24
1

You can add custom implementation of contains

private enum EventTypes {
    WORK, BREAK, WAIT, CLOSE, COMPLETE;

    public static boolean contains(String str) {
        for (EventTypes enumtype : values()) {
            if (enumtype.name().contains(str))
                return true;
        }
        return false;
    }
}

Then you can use it like below.

    System.out.println(EventTypes.contains("WORK"));
    System.out.println(EventTypes.contains("WOR"));

Remember enums are constants and I don't know what you will achieve doing this. You can read more about enums on Enum Types

Correct usage is

EventTypes enumType =EventTypes.valueOf("WORK");
0

Try it this way.....

enum EventTypes {
    WORK, BREAK, WAIT, CLOSE, COMPLETE
};





public class T {

    public static void main(String[] args) {



        for(EventTypes e : EventTypes.values()){


            if(e.name().equals("WORK")){

                System.out.println("True");
            }else{

                System.out.println("False");
            }
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.