【问题标题】:Enum doesn't initialize the correct value枚举没有初始化正确的值
【发布时间】:2015-11-27 16:42:17
【问题描述】:

我目前正在使用下面的枚举。

public enum ConditionCode  {
    EQ, SEQ, NE, SNE, CS, SCS, HS, SHS, CC, SCC, LO, SLO, MI, SMI, PL, SPL, VS, SVS, VC, 
    SVC, HI, SHI, LS, SLS,GE, SGE, LT, SLT, GT, SGT, LE, SLE, SAL, AL
}

我想获取枚举 ConditionCode.ALS 并打印它并通过这样做将其与 AL 进行比较

public static void main(String[] args)  {
    ConditionCode sal = ConditionCode.SAL;
    System.out.print(sal.toString + " ");
    System.out.println(sal.compareTo(ConditionCode.AL) == 0);
}

我觉得奇怪的是这个命令打印 AL 而不是 SAL false 并且对于所有其他枚举都是一样的,例如

public static void main(String[] args)  {
    ConditionCode cc = ConditionCode.CC;
    System.out.print(cc.toString + " ");
    System.out.println(cc.compareTo(ConditionCode.AL) == 0);
}

还将打印AL 而不是CC false。我能知道它为什么会这样吗?还有,我该如何解决?

【问题讨论】:

  • 您的代码无法编译。它将在sal.toString 失败(缺少括号)。
  • 它会因为它将使用 java.Lang.Enum.toString(),如果您必须更改枚举的输出,例如,如果您希望类中的所有枚举都打印 @ 987654330@ 你必须用类似public String toString(){ return 'S'; } 的东西覆盖函数 toString 否则默认 toString 是public String toString(){ return super.toString(); }
  • 投票关闭为拼写错误,请参阅 OP 对 Peter Lawrey 回答的评论。

标签: java enums


【解决方案1】:

这个程序http://ideone.com/uXiIj8按预期打印

public static void main (String[] args) throws java.lang.Exception
{
    {
        ConditionCode sal = ConditionCode.SAL;
        System.out.print(sal + " ");
        System.out.println(sal.compareTo(ConditionCode.AL) == 0);
    }
    {
        ConditionCode sal = ConditionCode.CC;
        System.out.print(sal + " ");
        System.out.println(sal.compareTo(ConditionCode.AL) == 0);
    }
}

public enum ConditionCode  {
   EQ, SEQ, NE, SNE, CS, SCS, HS, SHS, CC, SCC, LO, SLO, MI, SMI, PL, SPL, VS, SVS, VC, 
    SVC, HI, SHI, LS, SLS,GE, SGE, LT, SLT, GT, SGT, LE, SLE, SAL, AL
}

打印

SAL false
CC false

我能知道为什么会这样吗?还有,我该如何解决?

您很可能正在更改代码并在运行程序之前重新编译程序,或者您正在运行与您认为的程序不同的程序。我会确保您的 IDE 设置正确,以便在运行程序之前重新编译您的程序,如果它看起来不错,可能会重新启动它。

【讨论】:

  • 谢谢你的回答,但我发现问题出在我的代码中,我只是没有在我的函数中传递正确的参数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-01
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多