⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

Java 模式匹配:类型检查与解构

学习 instanceof 和 switch 中的模式匹配,简化类型检查和对象解构,写出更安全的代码。 · 难度:入门 · +15XP

传统 instanceof 的问题

if (obj instanceof String) {
    String s = (String) obj;  // 手动强制转换
    System.out.println(s.length());
}

需要先检查类型再强转,代码冗余且容易出错。

模式匹配 instanceof(Java 16+)

if (obj instanceof String s) {
    System.out.println(s.length());  // 直接使用 s
}

变量 s 的作用域限定在 if 块内,且仅在类型匹配时可用。

Switch 中的模式匹配(Java 17+ 预览)

String formatted = switch (obj) {
    case Integer i -> String.format("int %d", i);
    case String s  -> String.format("String %s", s);
    case null      -> "null";
    default        -> "unknown";
};

注意:null 也可以作为独立 case,避免空指针。

记录模式(Java 19+ 预览)

record Point(int x, int y) {}

if (obj instanceof Point(int x, int y)) { System.out.println("x=" + x + ", y=" + y); }

可以直接解构 record 的组件。

练习提示

在 starter_code 中,使用模式匹配 instanceof 判断对象类型并打印对应信息。

Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 133 篇
0 完成
🔥 0