Java21 Switch最全使用说明

Java21 Switch最全使用说明

Java 21 对 switch 语句进行了重大的改进和增强,使其变得更加灵活和强大。本文将详细介绍 Java 21 中 switch 语句的各种用法,包括基本语法、新特性、高级用法和最佳实践。

1. 基本语法
1.1 传统的 switch 语句

传统的 switch 语句支持 intcharbyteshortenum 类型的表达式。

public class TraditionalSwitchExample {
    public static void main(String[] args) {
        int number = 2;
        switch (number) {
            case 1:
                System.out.println("One");
                break;
            case 2:
                System.out.println("Two");
                break;
            case 3:
                System.out.println("Three");
                break;
            default:
                System.out.println("Unknown");
        }
    }
}
1.2 switch 语句作为表达式

从 Java 12 开始,switch 语句可以作为一个表达式使用,返回一个值。

public class SwitchExpressionExample {
    public static void main(String[] args) {
        int number = 2;
        String result = switch (number) {
            case 1 -> "One";
            case 2 -> "Two";
            case 3 -> "Three";
            default -> "Unknown";
        };
        System.out.println(result); // 输出 Two
    }
}
2. 新特性
2.1 类型模式匹配

Java 21 引入了类型模式匹配,允许在 switch 语句中直接匹配对象的类型,而无需显式的类型检查和转换。

public class TypePatternMatchingExample {
    public static void main(String[] args) {
        Object value = "Hello";
        String result = switch (value) {
            case String s -> s.length() + " characters";
            case Integer i -> i * 2 + " doubled";
            case null -> "Value is null";
            default -> "Unknown type";
        };
        System.out.println(result); // 输出 5 characters
    }
}
2.2 复杂表达式

switch 语句可以包含复杂的表达式,例如使用条件表达式。

public class ComplexExpressionExample {
    public static void main(String[] args) {
        String value = "YES";
        String result = switch (value) {
            case "YES" -> "You got it";
            case "NO" -> "Shame";
            default -> "Sorry?";
        };
        System.out.println(result); // 输出 You got it
    }
}
2.3 密封类模式匹配

Java 21 支持在 switch 语句中使用密封类模式匹配,这对于处理继承层次结构非常有用。

sealed interface S permits A, B, C { }
final class A implements S { }
final class B implements S { }
record C(int i) implements S { }

public class SealedClassPatternMatchingExample {
    public static void main(String[] args) {
        S s = new A();
        int result = switch (s) {
            case A a -> 1;
            case B b -> 2;
            case C(int i) -> i;
        };
        System.out.println(result); // 输出 1
    }
}
2.4 守卫条件

可以在 case 标签中添加守卫条件,以进一步细化匹配逻辑。

public class GuardClauseExample {
    public static void main(String[] args) {
        Integer number = 5;
        String result = switch (number) {
            case Integer i when i > 0 -> "Positive";
            case Integer i when i < 0 -> "Negative";
            case 0 -> "Zero";
            default -> "Unknown";
        };
        System.out.println(result); // 输出 Positive
    }
}
3. 高级用法
3.1 结合 var 关键字

Java 21 允许在 case 标签中使用 var 关键字,自动推断变量类型。

public class VarKeywordExample {
    public static void main(String[] args) {
        Object value = "Hello";
        String result = switch (value) {
            case String var s -> s.length() + " characters";
            case Integer var i -> i * 2 + " doubled";
            case null -> "Value is null";
            default -> "Unknown type";
        };
        System.out.println(result); // 输出 5 characters
    }
}
3.2 多个 case 标签

可以将多个 case 标签组合在一起,以减少重复代码。

public class MultipleCaseLabelsExample {
    public static void main(String[] args) {
        String value = "Hello";
        String result = switch (value) {
            case "Hello", "Hi" -> "Greeting";
            case "Bye" -> "Farewell";
            default -> "Unknown";
        };
        System.out.println(result); // 输出 Greeting
    }
}
3.3 default 分支

default 分支用于处理没有匹配到的任何情况。

public class DefaultBranchExample {
    public static void main(String[] args) {
        String value = "Unknown";
        String result = switch (value) {
            case "Hello" -> "Greeting";
            case "Bye" -> "Farewell";
            default -> "Unknown";
        };
        System.out.println(result); // 输出 Unknown
    }
}
4. 最佳实践
4.1 使用类型模式匹配

类型模式匹配可以显著减少代码量,提高可读性和维护性。

public class BestPracticeTypePatternMatching {
    public static void main(String[] args) {
        Object value = "Hello";
        String result = switch (value) {
            case String s -> s.length() + " characters";
            case Integer i -> i * 2 + " doubled";
            case null -> "Value is null";
            default -> "Unknown type";
        };
        System.out.println(result); // 输出 5 characters
    }
}
4.2 使用守卫条件

守卫条件可以增加匹配逻辑的灵活性,避免过多的嵌套判断。

public class BestPracticeGuardClause {
    public static void main(String[] args) {
        Integer number = 5;
        String result = switch (number) {
            case Integer i when i > 0 -> "Positive";
            case Integer i when i < 0 -> "Negative";
            case 0 -> "Zero";
            default -> "Unknown";
        };
        System.out.println(result); // 输出 Positive
    }
}
4.3 使用 var 关键字

var 关键字可以减少类型声明,使代码更加简洁。

public class BestPracticeVarKeyword {
    public static void main(String[] args) {
        Object value = "Hello";
        String result = switch (value) {
            case String var s -> s.length() + " characters";
            case Integer var i -> i * 2 + " doubled";
            case null -> "Value is null";
            default -> "Unknown type";
        };
        System.out.println(result); // 输出 5 characters
    }
}
5. 总结

通过本文的介绍,你应该已经对 Java 21 中 switch 语句的使用方法有了全面的了解。switch 语句的新特性使得代码更加简洁、易读和功能强大。通过掌握其基本语法、新特性、高级用法和最佳实践,可以编写出更加优雅、高效的代码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值