'Comparing enum and Long
I've got a simple enum and in my main() i want to compare this enum to Long variable, but I have an error HelloWorld.java:15: error: incomparable types: Long and myEnum System.out.println(x == myEnum.ENUM_A);. How to repair it and compare it correctly?
public class HelloWorld{
public enum myEnum {
ENUM_A(1),
ENUM_B(2),
ENUM_C(3);
int n;
private myEnum(int n) {
this.n = n;
}
}
public static void main(String []args){
Long x = 1L;
System.out.println(x == myEnum.ENUM_A);
}
}
Solution 1:[1]
You need to add a getN() to your enum:
public enum myEnum {
ENUM_A(1),
ENUM_B(2),
ENUM_C(3);
int n;
private myEnum(int n) {
this.n = n;
}
public int getN() {
return n;
}
}
and then in your main do System.out.println(x == myEnum.ENUM_A.getN());
If you need to compare any value, in your case a long with your enum, you will need to get the value of the enum.
Another alternative to the == is Objects from the java.util
Objects.equals(value1, value2)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ypdev19 |
