The comparison is returning false
because you're comparing a String
instance with an Enum
instance.
@RohitJain already gave a great explanation about why the toString()
method doesn't get called in your comparison in his answer, and how you should use it if it's what you want to do.
However, toString()
shouldn't be used for comparison purposes, it should be overriden only to provide a custom String representation of the object.
You could compare the property you're really intereseted in comparing if you do this:
String teststring = "1A".
Sysout(teststring.equals(Test.LETTER.getValue())); // Will return true
Of course you should provide a getter for the value
attribute or let it be visible to the operation doing the comparison.
You could also code a isEqual()
method in your enum
like this:
enum Test {
LETTER("1A");
private String value;
private Test(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
public boolean isEqual(String value) {
return this.value.equals(value);
}
}
And just do Test.LETTER.isEqual(teststring)
to do this comparison.
Or even a static getByValue(String value)
method to get the enum instance for a given value
:
enum Test {
...
public static Test getByValue(String val) {
for (Test c : values()) {
if (c.value.equals(val)) {
return c;
}
}
}
}
Test x = Test.getByValue("1A"); // x == Test.LETTER