Java Enum equals

Description

You can compare for equality an enumeration constant with any other object by using equals(). Those two objects will only be equal if they both refer to the same constant, within the same enumeration.

Example

Compare for equality an enumeration constant with any other object.


enum Direction {/*  w  ww.  ja  v a 2  s.  c  o m*/
  East, South, West, North
}

public class Main {
  public static void main(String args[]) {
    Direction ap = Direction.West;
    Direction ap2 = Direction.South;
    Direction ap3 = Direction.West;

    if (ap.equals(ap2)){
      System.out.println("Error!");
    }
      
    if (ap.equals(ap3)){
      System.out.println(ap + " equals " + ap3);
    }
      
    if (ap == ap3){
      System.out.println(ap + " == " + ap3);
    }
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Java Data Type »




Java Boolean
Java Byte
Java Character
Java Currency
Java Double
Java Enum
Java Float
Java Integer
Java Long
Java Short
Java Auto Grow Array
Java Array Compare
Java Array Convert
Java Array Copy Clone
Java Array Fill
Java Array Search and Sort
Java String Convert
Java String File
Java String Format
Java String Operation
Java BigDecimal
Java BigInteger