Search code examples
javaenumscomparison

Why are two enums incompatible with == operator?


I have a question: I don't know I can't compare two different enums with == operator. This is my code:

public class EnumExercises {

enum Seasons{
    SPRING, WINTER;

    Seasons() {
        System.out.println("Hello");
    }
}

enum TestResult {
    PASS, FAIL, SPRING; 
}
public static void main(String[] args) {
    Seasons s = Seasons.WINTER;
    Seasons s2 = Seasons.SPRING;
    TestResult t = TestResult.PASS;
    System.out.println(s2==t);  //incompatible...why?
    System.out.println(s2.equals(t));


}}

Thanks a lot.


Solution

  • For the same reason you can't say

    String s = "1";
    int t = 1;
    
    if (s == t) {
    

    s2 and t are of different types. They are not comparable.

    In the background, enum types compile out their names, so this wouldn't do what you want unless it coerces into compatible types. If you wanted to do this, you should use name() or toString(). See e.g. this answer.

    if (s2.name().equals(t.name())) {
    

    In general, == on objects checks if they refer to the same memory. That doesn't seem to be what you want to check here. You seem to be looking for the behavior on primitives (equal if the values are equal), which you won't get from object comparisons like this.