我有一个问题:我不知道我不能用 == 运算符比较两个不同的枚举。这是我的代码:
public class EnumExercises {
enum Seasons{
SPRING, WINTER;
Seasons() {
System.out.println("Hello");
}
}
enum TestResult {
PASS, FAIL, SPRING;
}
public static void main(String[] args) {
Seasons s = Seasons.WINTER;
Seasons s2 = Seasons.SPRING;
TestResult t = TestResult.PASS;
System.out.println(s2==t); //incompatible...why?
System.out.println(s2.equals(t));
}}
非常感谢。
最佳答案
出于同样的原因,你不能说
String s = "1";
int t = 1;
if (s == t) {
s2
和 t
是不同的类型。它们没有可比性。
在后台,枚举类型会编译出它们的名称,因此这不会执行您想要的操作,除非它强制转换为兼容类型。如果您想这样做,您应该使用 name()
或 toString()
。参见例如this answer 。
if (s2.name().equals(t.name())) {
一般来说,对象上的 ==
检查它们是否引用相同的内存。这似乎不是您要在这里检查的内容。您似乎正在寻找基元的行为(如果值相等则相等),而您不会从这样的对象比较中获得这种行为。
关于java - 为什么两个枚举与 == 运算符不兼容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53023427/