1
public enum EnumEqualsMethod {

    A,B,C

}


public enum EnumEqualsMethod1 {

    A,C,D

}

EnumEqualsMethod a =  EnumEqualsMethod.C;
ЕnumEqualsMethod1 b=  EnumEqualsMethod1.C;

System.out.println(a.equals(b));

Output is false.Why?

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
  • possible duplicate of [Comparing Java enum members: == or equals()?](http://stackoverflow.com/questions/1750435/comparing-java-enum-members-or-equals) – Smutje Dec 19 '14 at 11:36
  • Because that are two different objects. – Jens Dec 19 '14 at 11:36
  • It's not because they have the same name that they are equals. Even if they are enums, they are still objects. – Alexis C. Dec 19 '14 at 11:44

2 Answers2

5

Enums are compared as Objects. These are two distinct objects of different classes. Why should they be equal? A,B,C - are just names of variables. They mean nothing in comparison operation.

Mikhail
  • 4,175
  • 15
  • 31
  • we can't use equals method for constants in different enum classes.Right? – Furkan Aktaş Dec 19 '14 at 11:38
  • You should understand difference between reference, reference name and object. Once again reference names do not mean equality of objects. – Mikhail Dec 19 '14 at 11:40
  • 1
    You can use `equals()` for `enum` constants, but there's no point. It's the same as `==` for `enum`. One great thing about java `enum`s is that they each have their own name-space, so `C` in `EnumEqualsMethod` has nothing to do with `C` in `EnumEqualsMethod1`. – Paul Boddington Dec 19 '14 at 11:44
0

In order to understand why the output is false you should think of EnumEqualsMethod as a Class and A, B, C as Instances of that Class.

For example the comparison of the Enums is like doing the following:

Class1 a = new Class1();
Class2 b = new Class2();

System.out.print(a.equals(b));
Xipo
  • 1,765
  • 1
  • 16
  • 23