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,658
  • 4
  • 44
  • 80
  • 2
    the point of enums is they each have their own identity. why mess that up? – Nathan Hughes Jun 11 '16 at 00:13
  • 2
    @NathanHughes because Java allow it. – Asif Mushtaq Jun 11 '16 at 00:14
  • Just use `==` for identity comparisons, it works best. – markspace Jun 11 '16 at 00:15
  • @markspace `==` will not compare value. my logic is fine or not? – Asif Mushtaq Jun 11 '16 at 00:18
  • @Yassin I don't think so my question is duplicate. Just one line about why we can't override method is the reason? and you skipped all other lines that I asked? have you read my complete question? – Asif Mushtaq Jun 11 '16 at 00:19
  • i take responsibility for closing, I closed it because the other question already covered everything there is to say here. you're welcome to come up with things like comparevalue if that is helpful to you somehow. please understand the reason for closing is so we don't keep going over the same thing repeatedly. – Nathan Hughes Jun 11 '16 at 00:28

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
  • 764
  • 2
  • 7
  • 16