使用String的Java 7 switch语句是否使用equals()方法?

Nar*_*hai 32 java string equals switch-statement

Java 7支持切换,Strings如下面的代码

switch (month.toLowerCase()) {
case "january":
    monthNumber = 1;
    break;
case "february":
    monthNumber = 2;
    break;
default: 
    monthNumber = 0;
    break;
}
Run Code Online (Sandbox Code Playgroud)

Java是否equals()在每种String情况下调用该方法?或者,它依赖于==intern()

这简单地等同于:

String month = month.toLowerCase();
if("january".equals(month)){
monthNumber = 1;
}else if("february".equals(month)){
monthNumber = 1;
}..
Run Code Online (Sandbox Code Playgroud)

更新:

将switch表达式中的String与每个case标签关联的表达式进行比较,就好像String.equals正在使用该方法一样.

正如文档所指出的那样,行为就像equals()被调用一样.

Ani*_*kur 31

文件说,

The String in the switch expression is compared with the expressions associated
with each case label as if the String.equals method were being used.
Run Code Online (Sandbox Code Playgroud)

因为它说,好像我的猜测是它并不虽然内部实现是一样.equals()方法.


Ste*_*nar 9

The Java 7 switch statement actually generates bytecode that uses both the hashCode() and equals() methods. The hash code is used to generate faster switch lookups; i.e. to avoid a chain of equals checks like you would get with an if-else chain.


Ben*_*ale 6

是.

"与String一起使用时,switch语句使用equals()方法将给定的表达式与case语句中的每个值进行比较,因此区分大小写,如果表达式为null,则抛出NullPointerException."

http://java.dzone.com/articles/new-java-7-feature-string

  • 因为一些随机的博客帖子说它并不一定意味着它是正确的. (2认同)

Jun*_*san 5

switch与使用时声明String使用equals()方法为给定的表达比较在每个值case语句,并因此区分大小写和将抛出NullPointerException如果表达式null