class UseEnums2 {
enum Colors {
RED, GREEN, BLUE, YELLOW
}; public static void main(String[] args) {
for (Colors c : Colors.values()) {
if (c == Colors.GREEN)
System.out.print("green ");
if (Colors.RED.equals(c))
System.out.print("red ");
if (c == "YELLOW")
System.out.print("yellow ");
if (c.equals("BLUE"))
System.out.print("blue ");
}
}
}
enum Colors {
RED, GREEN, BLUE, YELLOW
}; public static void main(String[] args) {
for (Colors c : Colors.values()) {
if (c == Colors.GREEN)
System.out.print("green ");
if (Colors.RED.equals(c))
System.out.print("red ");
if (c == "YELLOW")
System.out.print("yellow ");
if (c.equals("BLUE"))
System.out.print("blue ");
}
}
}
比较对象类型不同
在枚举中如果没有对变量进行显式说明,默认的第一个变量的值是0,往后加1.
public boolean equals(Object obj);
参数为Object类型,所以即使你传错了,编译器也不会检查出问题。
class UseEnums2 {
enum Colors {
RED, GREEN, BLUE, YELLOW
}; public static void main(String[] args) {
for (Colors c : Colors.values()) {
if (c == Colors.GREEN)
System.out.print("green ");
if (Colors.RED.equals(c))
System.out.print("red ");
if (c == Colors.YELLOW)
System.out.print("yellow ");
if (c.equals("BLUE"))
System.out.print("blue ");
}
}
}red green yellow
Process completed.
因为类型不兼容嘛。
错误信息显示:不能将UseEnums2.Colors与一个String进行比较