我想我还没有在Java中得到Enum
的概念。如何比较字符串与Java中的switch语句中的枚举?
我尝试比较字符串与我的枚举条目可比较Special characters in an enum。
package com.stackoverflow.tests;
public class EnumTest {
enum EnumTestOperator {
EQUAL("=="),
NOT_EQUAL("!=");
private String value;
private EnumTestOperator(String value) {
this.value = value;
}
public String toString() {
// will return == or != instead of EQUAL or NOT_EQUAL
return this.value;
}
}
public static void main(String[] args) {
String line;
line = "<>";
line = ".ne.";
line = "!=";
// Operator
switch(line) {
// case "!=":
case EnumTestOperator.NOT_EQUAL:
System.out.println("Not Equal");
break;
default:
System.out.println("Something else");
break;
}
}
}
但在线路:
case EnumTestOperator.NOT_EQUAL:
我得到一个编译错误:
Type mismatch: cannot convert from EnumTest.EnumTestOperator to String
我在做什么错?
你混淆了不同类型的对象;因为Java是强类型的,这会导致错误 –