Enums contains only constants and can be compared directly with ==. So, only reference check is needed, no need to use .equals method. Moreover, if .equals used incorrectly, may raise the NullPointerException while that's not the case with == check.
enum Day { GOOD, AVERAGE, WORST; } public class Test { public static void main(String[] args) { Day day = null; if (day.equals(Day.GOOD)) {//NullPointerException! System.out.println("Good Day!"); } if (day == Day.GOOD) {//Always use == to compare enum System.out.println("Good Day!"); } } }
To group, complement, range the enum values we have EnumSet class which contains different methods.
enum Page { A1, A2, A3, A4, A5, A6, A7, A8, A9, A10 } public class Test { public static void main(String[] args) { EnumSet<Page> range = EnumSet.range(Page.A1, Page.A5); if (range.contains(Page.A4)) { System.out.println("Range contains A4"); } EnumSet<Page> of = EnumSet.of(Page.A1, Page.A5, Page.A3); if (of.contains(Page.A1)) { System.out.println("Of contains A1"); } } }
Say we have an enum DayOfWeek:
enum DayOfWeek { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; }
An enum is compiled with a built-in static valueOf() method which can be used to lookup a constant by its name:
String dayName = DayOfWeek.SUNDAY.name(); assert dayName.equals("SUNDAY"); DayOfWeek day = DayOfWeek.valueOf(dayName); assert day == DayOfWeek.SUNDAY;
This is also possible using a dynamic enum type:
Class<DayOfWeek> enumType = DayOfWeek.class; DayOfWeek day = Enum.valueOf(enumType, "SUNDAY"); assert day == DayOfWeek.SUNDAY;
Both of these valueOf() methods will throw an IllegalArgumentException if the specified enum does not have a constant with a matching name.
The Guava library provides a helper method Enums.getIfPresent() that returns a Guava Optional to eliminate explicit exception handling:
DayOfWeek defaultDay = DayOfWeek.SUNDAY; DayOfWeek day = Enums.valueOf(DayOfWeek.class, "INVALID").or(defaultDay); assert day == DayOfWeek.SUNDAY;
In case we want to use enum with more information and not just as constant values, and we want to be able to compare two enums.
Consider the following example:
public enum Coin { PENNY(1), NICKEL(5), DIME(10), QUARTER(25); private final int value; Coin(int value){ this.value = value; } public boolean isGreaterThan(Coin other){ return this.value > other.value; } }
Here we defined an Enum called Coin which represent its value. With the method isGreaterThan we can compare two enums:
Coin penny = Coin.PENNY; Coin dime = Coin.DIME; System.out.println(penny.isGreaterThan(dime)); // prints: false System.out.println(dime.isGreaterThan(penny)); // prints: true
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions