2025-08-12 18:10:04 +08:00

62 lines
2.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import java.util.*;
import java.util.stream.Collectors;
/**
* Java 10 新特性示例:局部变量类型推断 (Local-Variable Type Inference)
* 使用 var 关键字让编译器自动推断局部变量类型
*
* 这是Java 10最显著的特性之一简化了代码编写同时保持了Java的强类型特性
*/
public class VarExample {
public static void runExample() {
System.out.println("=== Java 10 局部变量类型推断示例 ===");
// 基本类型推断
var message = "Hello, Java 10!"; // 推断为 String
var number = 42; // 推断为 int
var decimal = 3.14159; // 推断为 double
var flag = true; // 推断为 boolean
System.out.println("String类型: " + message);
System.out.println("int类型: " + number);
System.out.println("double类型: " + decimal);
System.out.println("boolean类型: " + flag);
// 集合类型推断
var list = new ArrayList<String>(); // 推断为 ArrayList<String>
list.add("项目1");
list.add("项目2");
list.add("项目3");
System.out.println("\nArrayList内容:");
for (var item : list) { // 在增强for循环中使用var
System.out.println("- " + item);
}
// Map类型推断
var map = new HashMap<String, Integer>(); // 推断为 HashMap<String, Integer>
map.put("", 1);
map.put("", 2);
map.put("", 3);
System.out.println("\nHashMap内容:");
map.forEach((key, value) -> System.out.println(key + " -> " + value));
// 流处理中使用var
var numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
var evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println("\n流处理结果:");
evenNumbers.forEach(System.out::println);
// 在try-with-resources语句中使用var
try (var scanner = new Scanner(System.in)) {
System.out.println("\n在try-with-resources中使用var");
// var scanner = new Scanner(System.in); // 正常工作
}
System.out.println("\n=== 局部变量类型推断示例结束 ===\n");
}
}