【发布时间】:2022-06-12 20:42:48
【问题描述】:
我有一个数据结构,例如:
col1 col2 col3
A B A
C D E
F G F
H H H
有时单行中的值包含重复项,它们是指向同一行中其他值的回退。
我想知道,是否有一种优雅的方法可以通过 Java 中的枚举来解决这个问题?
那是我不想做的:
public class MyClass {
private enum MyEnum {
ROW1("A", "B", "A"),
ROW2("C", "D", "E"),
ROW3("F", "G", "F"),
ROW4("H", "H", "H");
private final String col1;
private final String col2;
private final String col3;
MyEnum(String col1, String col2, String col3) {
this.col1=col1;
this.col2=col2;
this.col3=col3;
}
}
public static void main(String args[]) {
System.out.println(MyEnum.ROW1.col3);
}
}
我希望做类似的事情:
public class MyClass {
private enum MyEnum {
ROW1("A", "B", equalsCol1()),
ROW2("C", "D", "E"),
ROW3(equalsCol3(), "G", "F"),
ROW4(equalsCol2(), "H", equalsCol2());
private final String col1;
private final String col2;
private final String col3;
MyEnum(String col1, String col2, String col3) {
this.col1=col1;
this.col2=col2;
this.col3=col3;
}
private static String equalsCol1() {
return this.col1;
}
private static String equalsCol2() {
return this.col2;
}
private static String equalsCol3() {
return this.col3;
}
}
public static void main(String args[]) {
System.out.println(MyEnum.ROW1.col3);
}
}
这显然会导致:
/MyClass.java:19: error: non-static variable this cannot be referenced from a static context
return this.col1;
^
/MyClass.java:22: error: non-static variable this cannot be referenced from a static context
return this.col2;
^
/MyClass.java:25: error: non-static variable this cannot be referenced from a static context
return this.col3;
^
3 errors
【问题讨论】:
-
您的问题到底是什么?现在编译它所需要的只是将
static修饰符添加到String equalsValue1()方法 -
我有一张表,有时 1 等于 2,1 等于 3,……或者有时它们都不同。我只想定义一次相等的值。
-
配合一些小辅助方法的使用。
-
您应该提供正确的输入和预期的输出。正如您所描述的,您需要布尔值而不是字符串