面试题答案
一键面试1. fall - through 含义
在Java的switch
语句中,fall - through
指的是当switch
表达式的值与某个case
常量值匹配时,从该case
开始执行代码,并且会继续执行后续case
的代码,直到遇到break
语句或者switch
语句结束。
2. 示例
int num = 2;
switch (num) {
case 1:
System.out.println("One");
case 2:
System.out.println("Two");
case 3:
System.out.println("Three");
break;
default:
System.out.println("Other");
}
上述代码中,num
的值为2,匹配case 2
,但由于没有break
,会继续执行case 3
的代码,输出:
Two
Three
3. 优化代码结构
- 使用多分支逻辑替代:将不同
case
中的逻辑提取到不同的方法中,根据switch
的结果调用相应方法。
int num = 2;
switch (num) {
case 1:
handleOne();
break;
case 2:
handleTwo();
break;
case 3:
handleThree();
break;
default:
handleOther();
}
void handleOne() {
System.out.println("One");
}
void handleTwo() {
System.out.println("Two");
}
void handleThree() {
System.out.println("Three");
}
void handleOther() {
System.out.println("Other");
}
- 使用
Map
替代:如果case
的值有一定规律,可以使用Map
来存储值与对应逻辑的映射关系。
import java.util.HashMap;
import java.util.Map;
public class SwitchOptimization {
public static void main(String[] args) {
int num = 2;
Map<Integer, Runnable> actionMap = new HashMap<>();
actionMap.put(1, () -> System.out.println("One"));
actionMap.put(2, () -> System.out.println("Two"));
actionMap.put(3, () -> System.out.println("Three"));
actionMap.getOrDefault(num, () -> System.out.println("Other")).run();
}
}
这样可以使代码结构更清晰,提高可读性和维护性,同时保证功能不变。