请看下面的代码:
int num = 0;
switch(num) {
case 1:
boolean bool = false;
break;
case 2:
String one;
String two;
String three;
//..simulating lots of vars
break;
default:
bool = true;
System.out.println(bool);
break;
}
由于我们可以引用在另一个case声明的变量,这意味着即使没有选择case 1
,boolean bool
仍然被声明。
由于default
是最后一个选项,而Java从左到右(从上到下)工作,我认为在case 2
(和任何其他case)中的变量也将被声明。
这让我想到在选择之前声明的case中有更多代码,与如果首先声明所选的case相比,实际访问该case需要更长的时间。
switch语句为什么要这样工作?如果有很多case,使用if-else
是否比switch语句更好?(谈论处理时间,纳秒)
{}
。 - Boris the Spiderswitch (...) { all cases belong to this context }
, 然后你也可以使用case ...: { this case now has own context }
;) - MadProgrammer