问题描述
由于各种商业原因,我想在我的一个类中保留一些静态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)
当我将它们更改为Integer时,我的switch语句出错。 表示Integer在交换机中应该没问题。
When I change them to Integer I get errors in my switch statement. The docs say that Integer should be ok within Switches.
报价
在我的代码中,如果我是 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.
我真的很蠢吗?或完全误读?
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 == ...
。只需与Integer
包装器进行比较时,只需要equals()
。
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 toInteger
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
.
这篇关于在Switch语句中使用Integer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!