在 Switch 语句中使用整数

2022-01-19 00:00:00 switch-statement java

出于各种业务原因,我想在我的一个类中保存一些静态 ID.它们最初是 int 但我想将它们更改为 Integer 以便我可以对它们进行等于(即 MY_ID.equals(..)避免 NPE)

For various business reasons I want to hold some static IDs in one of my classes. They were originally int but I wanted to change them to Integer so I could do an equals on them (ie MY_ID.equals(..) which avoids NPEs)

当我将它们更改为整数时,我的 switch 语句中出现错误.docs 说 Integer 在 Switch 中应该没问题.

When I change them to Integer I get errors in my switch statement. The docs say that Integer should be ok within Switches.

引用

[Switch] 也适用于枚举类型(在枚举类型中讨论),String 类,以及一些包装某些特定类的特殊类原始类型:Character、Byte、Short 和 Integer(在数字和字符串).

[Switch] also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings).

在我下面的代码中,如果 i 是 int 则它会编译.当它是 Integer 时,它并不表示需要 常量表达式.我试过做 .intValue() 但这也不起作用.

In my code below if i is a int then it compiles. When it is an Integer it doesnt saying that a constant expression is required. I have tried doing .intValue() but this doesnt work either.

我真的很傻吗?还是完全误读了 docs?

Am I being really stupid? Or completely misreading the docs?

private static final Integer i = 1;

@Test
public void test() {
    switch(mObj.getId()){
        case i: //do something
        default: //do something default
    }

}

感谢您在此提供的任何指示.目前我将它们保留为 int 并执行 new Integer(myint).equals(...)

Thanks for any pointers here. For the time being I am keeping them as int and doing new Integer(myint).equals(...)

推荐答案

将常量更改为原始类型:

Change your constant to primitive type:

private static final int i = 1;

你会没事的.switch 只能处理原语、枚举值和(从 Java 7 开始)字符串.小贴士:

and you'll be fine. switch can only work with primitives, enum values and (since Java 7) strings. Few tips:

  • new Integer(myint).equals(...) 可能是多余的.如果至少有一个变量是原始的,只需执行:myint == ....equals() 仅在与 Integer 包装器比较时才需要.

  • new Integer(myint).equals(...) might be superflous. If at least one of the variables is primitive, just do: myint == .... equals() is only needed when comparing to Integer wrappers.

首选 Integer.valueOf(myInt) 而不是 new Integer(myInt) - 并尽可能依赖自动装箱.

Prefer Integer.valueOf(myInt) instead of new Integer(myInt) - and rely on autoboxing whenever possible.

常量在 Java 中通常使用大写,所以 static final int I = 1.

Constant are typically written using capital case in Java, so static final int I = 1.

相关文章