0

I want to compare Enum's value as in example.

public enum En{
    Vanila("Good"),
    Marlena("Luck"),
    Garnela("Good");

    private String value;

    private En(String s){
        this.value = s;
    }
}

AS Vanila and Garnela have the same value comparing them should return true. There are two ways one is == operator and second is equals() method. I tried my own logic and add this method to enum.

public boolean compareValue(En e){
        return (this.value).equals(e.value);
}

and Now it's working fine.

En a = En.Vanila;
En b = En.Garnela;
En c = En.Marlena;

if(a.compareValue(b)){
    System.out.println("a == b");
}
if(a.compareValue(c)){
    System.out.println("a == c");
}
if(b.compareValue(c)){
    System.out.println("b == c");
}

I know we can't override equals methods in enum ( Don't know why, I know that is final but not a logically reason. Can you also explain, why we can't override equals() in enum?).

Any how is there any other way to do this effectively or is it fine?

Asif Mushtaq
  • 3,332
  • 2
  • 38
  • 69

1 Answers1

1

In enum each instance is meant to represent a distinguished thing. The enum value is used to describe that thing, make it human readable, etc.

Therefore there's no reason for your code to consider that Vanilla could be equal to Marlena. And it makes no sense to set the same string values for both of them.

Bruno Negrão Zica
  • 620
  • 2
  • 7
  • 15