Compare enum and string java

How to compare enum with string in java

Solution 3: to compare enum to string Solution 1: The method first checks if the passed argument is an instance of or not. Just stop using enums and declare them as string constants: Then you can use them in the switch/case.

How to compare string to enum type in Java?

public void setState(String s)

You might want to handle the IllegalArgumentException that may be thrown if «s» value doesn’t match any «State»

Use .name() method. Like st.name() . e.g. State.AL.name() returns string «AL».

if(st.name().equalsIgnoreCase(s))  

to compare enum to string

for (Object s : State.values()) < if (theString.equals(s.toString())) < // theString is equal State object >> 

Comparing ENUMs in Java 6, There's a lot of problems with the code that you posted (it won't compile without fixing a lot of errors), but the easiest way is to make Traveler …

Enum String comparison in JAVA

The String#equals(Object) method first checks if the passed argument is an instance of String or not. Here's a snippet of the source code:

public boolean equals(Object anObject) < if (this == anObject) < return true; >if (anObject instanceof String) < // Code [. ] >return false; > 

Since Foo.TEST1 is not an instance of String , it returns false .

Q. I want to compare a String with an Enum

Enum provides a name() method. You need to use that to be able to compare a enum object with a String because the equals() method checks if the argument is a String instance or not. And since it is not, it'd would return false .

likeEnumTest1.equals(Foo.TEST1.name()) 

This can be seen from the source code of equals() of String class

public boolean equals(Object anObject) < // It takes an object and even enum is an object, thus it doesn't call the `toString()` method. if (this == anObject) < return true; >if (anObject instanceof String) < String anotherString = (String)anObject; int n = count; if (n == anotherString.count) < char v1[] = value; char v2[] = anotherString.value; int i = offset; int j = anotherString.offset; while (n-- != 0) < if (v1[i++] != v2[j++]) return false; >return true; > > return false; > 

Java - Compare a list of enum values with a single enum, You are comparing List and Enum with equal which always return false. If you use contains instead of equals, the condition will work. if …

What's the proper way to compare a String to an enum value?

I'm gathering from your question that userPick is a String value. You can compare it like this:

if (userPick.equalsIgnoreCase(computerPick.name())) . . . 

As an aside, if you are guaranteed that computer is always one of the values 1 , 2 , or 3 (and nothing else), you can convert it to a Gesture enum with:

Gesture computerPick = Gesture.values()[computer - 1]; 

You should declare toString() and valueOf() method in enum .

 import java.io.Serializable; public enum Gesture implements Serializable < ROCK,PAPER,SCISSORS; public String toString()< switch(this)< case ROCK : return "Rock"; case PAPER : return "Paper"; case SCISSORS : return "Scissors"; >return null; > public static Gesture valueOf(Class enumType, String value) < if(value.equalsIgnoreCase(ROCK.toString())) return Gesture.ROCK; else if(value.equalsIgnoreCase(PAPER.toString())) return Gesture.PAPER; else if(value.equalsIgnoreCase(SCISSORS.toString())) return Gesture.SCISSORS; else return null; >> 
public enum SomeKindOfEnum < ENUM_NAME("initialValue"); private String value; SomeKindOfEnum(String value)< this.value = value; >public boolean equalValue(String passedValue) < return this.value.equals(passedValue); >> 

And if u want to check Value u write:

SomeKindOfEnum.ENUM_NAME.equalValue("initialValue") 

Kinda looks nice for me :). Maybe somebody will find it useful.

Java - struts 2 if, In that case, you are comparing a CaterogyEnum to a string in your OGNL expression, so that's why it is failing. Can you use real Java 1.5 enums, or …

How to compare string to enum in a switch statement in Java?

You are comparing incompatible types. It's similar to the statement

"some string" == EnumTestOperator.NOT_EQUAL 

where your compare a string value to an enum constant.

Just stop using enums and declare them as string constants:

private static final String EQUAL = "=="; private static final String NOT_EQUAL = "!="; 

Then you can use them in the switch/case.

The other solution would be to find the enum constant based on your input. Add this to your enum:

public static EnumTestOperator byValue(String val) < for(EnumTestOperator en:values())< if(en.value.equals(val))< return en; >> return null; > 

And then use the function like this:

EnumTestOperator en = EnumTestOperator.byValue(line); switch(en)

Unfortunately you will have to handle the null case differently since putting a null into a switch will throw a NullPointerException .

EnumTestOperator.NOT_EQUAL is an instance of EnumTestOperator . You cannot compare it with a String .

You can evenutually compare EnumTestOperator.NOT_EQUAL.toString() with a String but not in a case statement ( case statements require constant expressions in Java).

But you can instead iterate on EnumTestOperator constants :

public static EnumTestOperator find(String strValue) < for(EnumTestOperator operator : EnumTestOperator.values()) < if(operator.toString().equals(strValue)) < return operator; >> throw new IllegalArgumentException("No matching value"); > 

How to get an enum value from a string value in Java, An enum class automatically gets a static valueOf () method in the class when compiled. The valueOf () method can be used to obtain an instance of the enum …

Источник

Tech Tutorials

Tutorials and posts about Java, Spring, Hadoop and many more. Java code examples and interview questions. Spring code examples.

Thursday, March 16, 2023

Comparing Enum to String in Java

Sometimes you may have the scenario where you want to compare String to enum type in Java. For example you may have an enum with product codes and you want to check that the passed produce code is one of the predefined product codes or not.

Here one thing to note is directly comparing enum value with a string won't work as they both will be of different types.

For example, notice in the code snippet given below where enum type d is directly compared with the String, it won't give any output as they will never be equal.

enum Day < SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY >public class EnumDemo < public static void main(String[] args) < EnumDemo ed = new EnumDemo(); ed.checkDay("TUESDAY"); >private void checkDay(String str) < Day[] allDays = Day.values(); for(Day d : allDays)< if(d.equals(str))< System.out.println("Day of week- " + d.name()); >> > >

Comparing String to Enum type in Java

  • toString()- Returns the name of this enum constant, as contained in the declaration.
  • name()- Returns the name of this enum constant, exactly as declared in its enum declaration.

Using toString() method to compare enum to String in Java

enum Day < SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY >public class EnumDemo < public static void main(String[] args) < EnumDemo ed = new EnumDemo(); ed.checkDay("TUESDAY"); >private void checkDay(String str) < Day[] allDays = Day.values(); for(Day d : allDays)< //Comparing if(d.toString().equals(str))< System.out.println("Day of week- " + d.name()); >> > >

That will work as desired and give you the output - Day of week- TUESDAY

Using name() method to compare enum to String in Java

Enum class also has a name() method that returns the name of this enum constant, exactly as declared in its enum declaration. Though a word of caution here according to Java docs -

"Most programmers should use the toString() method in preference to this one, as the toString method may return a more user-friendly name. This method is designed primarily for use in specialized situations where correctness depends on getting the exact name, which will not vary from release to release."

enum Day < SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY >public class EnumDemo < public static void main(String[] args) < EnumDemo ed = new EnumDemo(); ed.checkDay("TUESDAY"); >private void checkDay(String str) < Day[] allDays = Day.values(); for(Day d : allDays)< if(d.name().equals(str))< System.out.println("Day of week- " + d.name()); >> > >

Using name() method also gives the desired output - Day of week- TUESDAY

That's all for this topic Comparing Enum to String in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Источник

How to Compare String to Enum Java

How to Compare String to Enum Java? The Enum is a keyword used while defining enumeration which contains constant values which are accessible. Enum expands as enumeration. The string is a collection of a sequence of characters that are represented between double quotes (“ ”). Now in this blog, we are comparing the string to an enum.

Program to Compare String to Enum Java

Here we are comparing the enum of days to the string, this is obviously not equal hence the result will be not equal. The enum is a different type and the string is different while comparing it is not equal. Check the below program.

enum Day < SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY >public class Main < public static void main(String[] args) < Main obj = new Main(); obj.checkEnum("TUESDAY"); >private void checkEnum(String string) < Day[] Days = Day.values(); for (Day day : Days) < System.out.println("Day: " + day.name()); if (day.equals(string)) < System.out.println("Equal"); >else < System.out.println("Not equal"); >> > >

Day: SUNDAY
Not equal
Day: MONDAY
Not equal
Day: TUESDAY
Not equal
Day: WEDNESDAY
Not equal
Day: THURSDAY
Not equal
Day: FRIDAY
Not equal
Day: SATURDAY
Not equal

How To Compare Enum With String In Java

As we saw in the above program the string and enum cannot be compared directly even if it looks the same as the types are different which might result in inequality, so to overcome this we need to first convert the enum value to string and then compare to do this here we are using toString() method.

enum Day < SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY >public class Main < public static void main(String[] args) < Main obj = new Main(); obj.checkEnum("TUESDAY"); >private void checkEnum(String string) < Day[] Days = Day.values(); for (Day day : Days) < System.out.println("Day: " + day.name()); if (day.toString().equals(string)) < System.out.println("Equal"); break; >else < System.out.println("Not equal"); >> > > 

Day: SUNDAY
Not equal
Day: MONDAY
Not equal
Day: TUESDAY
Equal

Now let us see the same thing with the name() method. The name() method yields the same output as the toString() method but the difference is the name() method returns the enum constant that is exactly as same as the one in the declaration. The toString() method returns which are contained in the declaration.

enum Day < SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY >public class Main < public static void main(String[] args) < Main obj = new Main(); obj.checkEnum("TUESDAY"); >private void checkEnum(String string) < Day[] Days = Day.values(); for (Day day : Days) < System.out.println("Day: " + day.name()); if (day.name().equals(string)) < System.out.println("Equal"); break; >else < System.out.println("Not equal"); >> > > 

Day: SUNDAY
Not equal
Day: MONDAY
Not equal
Day: TUESDAY
Equal

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Источник

Читайте также:  Using sound in java
Оцените статью