Java equals with enum

How To Compare Enum Members Using == Or Equals() Method In Java?

Enum is the short form of enumeration, which means specifically listed or a list of named constants.

Enum was first introduced in Java 5. It contains a fixed set of constants. It can also contain methods. It can be used to store directions (NORTH, SOUTH, EAST, WEST), days(SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY), colors(VIOLET, BLUE, YELLOW, PINK, GREEN, BLACK, WHITE), etc.

According to the Java naming convention, we should have all the constants in capital letters. So, we have written in capital letters.

There are two ways for comparing the enum in Java:

Let’s understand one by one with code examples.

Comparing enum By using == operator in Java

The == operator is a binary operator. It compares the two operands and returns either true or false. It never throws NullPointerException.

Читайте также:  Python tkinter label left

In the below example, we are comparing an enum member with a null. So here we are not getting any exception. For better understanding see the example below.

// Java code to demonstrate enum members comparison by using == operator. class JavaExercise <   public enum Month <     JAN,     FEB,     MAR,     APR,     MAY,     JUN,     JUL,     SEPT,     OCT,     NOV,     DEC  >​   public static void main(String[] args) <     Month m = null; ​     // Comparing an enum member with null     // using == operator     System.out.println(m == Month.FEB);  >>

Let’s take one more example. Here, we have used the Days enum to compare its values by using the == operator. The first value will return false and the second will return true. See the example below.

// Java program to demonstrate enum members comparison by using == operator. enum Days <   MON,   TUE,   WED,   THU,   FRI,   SAT,   SUN >public class JavaExercise <   public static void main(String[] args) <     boolean result = isSun(Days.WED);     System.out.println(result);     result = isSun(Days.SUN);     System.out.println(result);  >​   public static boolean isSun(Days day) <     if (day == Days.SUN) <       return true;    >    return false;  > >

Comparing two different enum using == operator in Java

In the below code, we have compared an enum member with another enum member. We have used the == operator for comparison.

Here, we are getting compilation failure. So from this, we can conclude that when we use == operator for enum member comparison then it performs type compatibility check at the compile time.

// Java program to demonstrate enum members comparison class JavaExercise <   public enum Day <     MON,     TUE,     WED,     THU,     FRI,     SAT,     SUN  >​   public enum Month <     JAN,     FEB,     MAR,     APR,     MAY,     JUN,     JULY  >​   public static void main(String[] args) <     // Comparing two enum members which are from different enum type     // using == operator     System.out.println(Month.JAN == Day.MON); ​  >>
JavaExercise.java:26: error: incomparable types: Month and Day    System.out.println(Month.JAN == Day.MON);                   ^

Comparing enum By using equals() method in Java

In Java, the equals() method compares two values and returns a boolean value, either true or false. We can use this method for comparing enum. The equals() method throws NullPointerException if the enum is null.

In the below example, we are comparing an enum member with a null. So here we are getting NullPointerException. For better understanding see the example below.

// Java program to demonstrate enum members comparison using equals() method. class JavaExercise <   public enum Month <     JAN,     FEB,     MAR,     APR,     MAY,     JUN,     JUL,     SEPT,     OCT,     NOV,     DEC  >​   public static void main(String[] args) <     Month m = null; ​     // Comparing an enum member with null     // using .equals() method     System.out.println(m.equals(Month.FEB));  >>
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "JavaExercise$Month.equals(Object)" because "" is null    at JavaExercise.main(JavaExercise.java:22)

let’s take another example. Here, we have used the Days enum to compare its values by using the equals() method. The first value will return false and the second will return true.

// Java program to demonstrate enum members comparison using equals() method. enum Days <   MON,   TUE,   WED,   THU,   FRI,   SAT,   SUN >​ public class JavaExercise <   public static void main(String[] args) <     boolean result = isSun(Days.WED);     System.out.println(result);     result = isSun(Days.SUN);     System.out.println(result);  >​   public static boolean isSun(Days day) <     if (day.equals(Days.SUN)) <       return true;    >    return false;  > >

Comparing two different enum using equals() method in Java

In the below code, we have compared an enum member with another enum member. We have used the equals() method for comparison. Here, we are not getting any compilation failure. So from this, we can conclude that the equals() method never worries about the types of both the arguments (it gives false for the incomparable types).

// Java program to demonstrate enum members comparison class JavaExercise <   public enum Day <     MON,     TUE,     WED,     THU,     FRI,     SAT,     SUN  >​   public enum Month <     JAN,     FEB,     MAR,     APR,     MAY,     JUN,     JULY  >​   public static void main(String[] args) < ​     // Comparing two enum members which are from different enum type     // using .equals() method     System.out.println(Month.JAN.equals(Day.MON));  >>

Источник

Как лучше сравнивать перечисляемые типы в Java

Обложка: Как лучше сравнивать перечисляемые типы в Java

Недавно на Stack Overflow я наткнулся на, казалось бы, простой вопрос:

Что лучше использовать для сравнения enum’ов — == или equals() ?

Вы, конечно, можете сходу ответить, что никакой разницы нет, но будете неправы — в ответах к этому вопросу было приведено много интересных аргументов в пользу обоих вариантов. Я решил, что будет интересно перевести этот спор на русский язык.

Они же оба работают, верно?

Да. Как написано в документации, «допустимо использовать оператор == вместо метода equals , если доподлинно известно, что хотя бы один из них ссылается на перечислимый тип» («it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant»). Причина этого очень простая — каждый из объектов enum’а создаётся только единожды, и поэтому, если вы создадите десять переменных равных SomeEnum.RED , они все будут ссылаться на один и тот же объект (а оператор == как раз это и проверяет).

Какие есть преимущества у оператора ==?

enum Color < BLACK, WHITE >; Color nothing = null; if (nothing == Color.BLACK); // Всё отлично if (nothing.equals(Color.BLACK)); // выбрасывает NullPointerException
enum Color < BLACK, WHITE >; enum Chiral < LEFT, RIGHT >; if (Color.BLACK.equals(Chiral.LEFT)); // Компилируется if (Color.BLACK == Chiral.LEFT); // НЕ КОМПИЛИРУЕТСЯ. Несовместимые типы!

Ого, как серьёзно все подошли к вопросу! Ну теперь точно буду использовать оператор равенства.

Не спешите так. Не все единогласно за == . Вот что пишут сторонники equals() :

  • Нет ни единого случая, когда переменная перечисляемого типа должна быть равна null — если вы так описываете какое-то особое состояние, то его можно просто заменить на ещё одно допустимое состояние enum’а. А значит, NPE не надо скрывать, так как это, вероятнее всего, ошибка, и чем раньше о ней станет известно, тем лучше.
  • Аргумент про скорость == весьма сомнителен. Современные компиляторы, скорее всего умеют заменять equals на == самостоятельно. Если это не так (как доказали позже, это действительно не так), то это проблема Java, над которой нужно работать.
  • Какой Java-программист не знает, что делает equals ? Такой вариант наоборот более читаем, так как для объектов мы привыкли использовать именно метод equals . Значит, и для enum’ов нужно поступать так же, чтобы не возникало путаницы.

Источник

Compare Java Enum Using == or equals() Method in Java

Compare Java Enum Using == or equals() Method in Java

  1. Compare Enum Using the == Operator in Java
  2. Compare Enum Using the equals() Method in Java
  3. Compare Enum Values and Handle null Safety
  4. Compare Two Different Enum Values in Java

This tutorial introduces how to compare Java enum using the == operator or equals() method in Java.

Enum is a set of constants used to collect data sets such as day, month, color, etc. In Java, to create an enum, we use the enum keyword and then provide values for the type.

This article will demonstrate how to compare the enum values and objects. Let’s understand with some examples.

Compare Enum Using the == Operator in Java

The == (equal) operator is a binary operator that requires two operands. It compares the operands and returns either true or false .

We can use this to compare enum values. See the example below.

enum Color  red,  green,  yello,  white,  black,  purple,  blue; >  public class SimpleTesting  public static void main(String[] args)  boolean result = isGreen(Color.blue);  System.out.println(result);  result = isGreen(Color.green);  System.out.println(result);  >   public static boolean isGreen(Color color)   if(color == Color.green)   return true;  >  return false;  > > 

Compare Enum Using the equals() Method in Java

Java equals() method compares two values and returns a boolean value, either true or false . We can use this method to compare enum values.

Here, we used the Color enum to compare its values. The first value returns false , but it returns true for the second. See the example below.

enum Color  red,  green,  yello,  white,  black,  purple,  blue; >  public class SimpleTesting  public static void main(String[] args)  boolean result = isGreen(Color.blue);  System.out.println(result);  result = isGreen(Color.green);  System.out.println(result);  >   public static boolean isGreen(Color color)   if(color.equals(Color.green))   return true;  >  return false;  > > 

Compare Enum Values and Handle null Safety

In Java, the most problematic issue is handling null values. It also applies to the enum comparison; if we use the equals() method to compare enum values and the enum object is null , it throws nullpointerexception . See the example below.

enum Color  red,  green,  yello,  white,  black,  purple,  blue; > public class SimpleTesting  public static void main(String[] args)  Color color = null;  boolean result = isGreen(color);  System.out.println(result);  result = isGreen(Color.green);  System.out.println(result);  >  public static boolean isGreen(Color color)   if(color.equals(Color.green))   return true;  >  return false;  > > 
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "javaexample.Color.equals(Object)" because "color" is null 

However, if we work with the == (equals) operator and compare enum values/objects, it will not throw the nullpointerexception . That means this operator is null safe and better to use than the equals() method. See the example below.

enum Color  red,  green,  yello,  white,  black,  purple,  blue; >  public class SimpleTesting  public static void main(String[] args)  Color color = null;  boolean result = isGreen(color);  System.out.println(result);  result = isGreen(Color.green);  System.out.println(result);  >   public static boolean isGreen(Color color)   if(color == Color.green)   return true;  >  return false;  > > 

Compare Two Different Enum Values in Java

We can also compare two enum objects using the equals() method. Since both the objects are different, it returns false in both cases. See the example below.

enum Color  red,  green,  yello,  white,  black,  purple,  blue; >  enum MyColors  green,  red,  blue; >  public class SimpleTesting  public static void main(String[] args)  boolean result = isGreen(Color.red);  System.out.println(result);  result = isGreen(Color.green);  System.out.println(result);  >   public static boolean isGreen(Color color)   if(color.equals(MyColors.red))   return true;  >  return false;  > > 

Related Article — Java Enum

Источник

Оцените статью