How to compare two enums in java

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.

  • EnumSet#range : To get subset of enum by range defined by two endpoints

  • EnumSet#of : Set of specific enums without any range. Multiple overloaded of methods are there.

  • EnumSet#complementOf : Set of enum which is complement of enum values provided in method parameter

    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"); } } }

How to compare two enums in java
PDF - Download Java Language for free

xxtesaxx answer at 2017-05-19 171


The trick is to not actually check with == but rather use the case keyword in conjunction with a single = in your if statement. This is a little counter intuitive in the beginning but just like if let, you get used to it pretty fast:


enum Normal { case one case two, three } enum NormalRaw: Int { case one = 1 case two, three } enum NormalArg { case one(Int) case two, three } let normalOne = Normal.one let normalRawOne = NormalRaw.one let normalArgOne = NormalArg.one(1) if case .one = normalOne { print("A normal one") //prints "A normal one" } if case .one = normalRawOne { print("A normal \(normalRawOne.rawValue)") //prints "A normal 1" } if case .one(let value) = normalArgOne { print("A normal \(value)") //prints "A normal 1" }

The point is that in Swift you only get equation of enums for free if your enum uses a raw type or if you have no associated values (try it out, you can't have both at the same time). Swift however does not know how to compare cases with associated values - I mean how could it? Let's look at this example:


Normal.one == .one //true Normal.one == .two //false NormalRaw.one == .one //true NormalRaw.one == .two //false NormalArg.one(1) == .one(1) //Well...? NormalArg.one(2) == .one(1) //Well...? NormalArg.one(1) == .two //Well...?

Maybe this makes it clearer why this cannot work out of the box:


class Special { var name: String? var special: Special? } enum SpecialEnum { case one(Special) case two } var special1 = Special() special1.name = "Hello" var special2 = Special() special2.name = "World" special2.special = special1 SpecialEnum.one(special1) == SpecialEnum.one(special2) //Well...?

So if you want enums with associated values, you'll have to implement Equatable protocol in your enum by yourself:


enum NormalArg: Equatable { case one(Int) case two static func ==(lhs: NormalArg, rhs: NormalArg) -> Bool { switch (lhs, rhs) { case (let .one(a1), let .one(a2)): return a1 == a2 case (.two,.two): return true default: return false } } }

How to compare two enums in java

Sometime back I’ve written an article on Java eNum – Why and for what should I use Java eNum?

What is an eNum type?

It is a special data type to which we could assign predefined constants to variable.

In this tutorial we will go over how to compare eNums in your production application. As previous tutorial gives you complete example and details on eNum, this tutorial provides complete insight on comparison part.

There are three ways we could compare eNum in Java.

  1. Switch-Case Statement
  2. == Operator
  3. .equals() method

Also if you have below questions then you are at right place.

  • Comparing Java enum members
  • Use == (or !=) to Compare Java Enums
  • Java.lang.Enum.compareTo()
  • How to Compare Two Enum in Java
  • == or equals with Java enum
  • enum comparison in java
  • enum comparison string java

Let’s get started:

Step-1

Create eNum CrunchifyCompany.java in Eclipse IDE.

package crunchify.com.tutorial;

public enum CrunchifyCompany {

GOOGLE, FACEBOOK, YAHOO, TWITTER, CRUNCHIFY

Step-2

Create class CrunchifyCompanyEnumTest.java which implements comparison methods using equals (==) and using switch case.

CrunchifyCompanyEnumTest.java

package crunchify.com.tutorial;

* @author Crunchify.com, version: 1

public class CrunchifyCompanyEnumTest {

public static void main(String[] args) {

// Let's check eNum using Switch-Case statement

log("Comparison using Switch-Case ========================");

crunchifyEnumTestUsingSwitch(CrunchifyCompany.FACEBOOK);

crunchifyEnumTestUsingSwitch(CrunchifyCompany.TWITTER);

// Let's check eNum using Equal (==) operator

log("\nComparison using == operator ========================");

crunchifyEnumTestUsingEqualSign(CrunchifyCompany.CRUNCHIFY);

crunchifyEnumTestUsingEqualSign(CrunchifyCompany.YAHOO);

// Let's check eNum using .equals() method

log("\nComparison using .equals() ========================");

crunchifyEnumTestUsingEqualsMethod(CrunchifyCompany.FACEBOOK);

crunchifyEnumTestUsingEqualsMethod(CrunchifyCompany.GOOGLE);

private static void log(String str) {

// Method-1: Using Switch-Case

private static void crunchifyEnumTestUsingSwitch(CrunchifyCompany company) {

// NOTE: we haven't added switch case for TWITTER intentionally here

log("Enum check PASSED for: GOOGLE");

log("Enum check PASSED for: FACEBOOK");

log("Enum check PASSED for: YAHOO");

log("Enum check PASSED for: CRUNCHIFY");

log("Enum check FAILED for company: " + company);

// Method-2: Using == Operator

private static void crunchifyEnumTestUsingEqualSign(CrunchifyCompany company) {

// NOTE: we haven't added switch case for GOOGLE intentionally here

if (company == CrunchifyCompany.FACEBOOK) {

log("Enum check PASSED for: FACEBOOK");

} else if (company == CrunchifyCompany.TWITTER) {

log("Enum check PASSED for: TWITTER");

} else if (company == CrunchifyCompany.YAHOO) {

log("Enum check PASSED for: YAHOO");

} else if (company == CrunchifyCompany.CRUNCHIFY) {

log("Enum check PASSED for: CRUNCHIFY");

log("Enum check FAILED for company: " + company);

// Method-3: Using equals()

private static void crunchifyEnumTestUsingEqualsMethod(CrunchifyCompany company) {

if (company.equals(CrunchifyCompany.FACEBOOK)) {

log("Enum check PASSED for: FACEBOOK");

log("Enum check FAILED for company: " + company);

Step-3

Run the program to see result.

Comparison using Switch-Case ========================

Enum check PASSED for: FACEBOOK

Enum check FAILED for company: TWITTER

Comparison using == operator ========================

Enum check PASSED for: CRUNCHIFY

Enum check PASSED for: YAHOO

Comparison using .equals() ========================

Enum check PASSED for: FACEBOOK

Enum check FAILED for company: GOOGLE

If you liked this article, then please share it on social media. Still have any questions about an article, leave us a comment.