【问题标题】:Reference to another value within the same enumeration in Java [closed]引用Java中同一枚举中的另一个值[关闭]
【发布时间】: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,……或者有时它们都不同。我只想定义一次相等的值。
  • 配合一些小辅助方法的使用。
  • 您应该提供正确的输入和预期的输出。正如您所描述的,您需要布尔值而不是字符串

标签: java enums


【解决方案1】:

这样就行不通了——你不能调用一个类的构造函数并传递同一个类的方法调用的结果。

要么将equalsValue1()设为静态,要么从构造函数内部调用方法。

即使这样(从构造函数内部调用)也是危险的,因为您调用了一个不容易初始化的对象的方法。注意不要将对正在构建的对象 (this) 的任何引用传递到类之外的任何地方。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    • 2017-04-01
    • 2014-02-16
    • 1970-01-01
    相关资源
    最近更新 更多