package com.lfsun.java9study.collectionfactory;import java.util.*;public class CollectionFactoryExample {public static void main(String[] args) {// 创建不可变列表List<String> list = List.of("apple", "banana", "orange");System.out.println("List: " + list);// 创建不可变集合Set<String> set = Set.of("apple", "banana", "orange");System.out.println("Set: " + set);// 创建不可变映射Map<String, Integer> map = Map.of("apple", 1, "banana", 2, "orange", 3);System.out.println("Map: " + map);// 创建不可变映射(多个键值对)Map<String, Integer> mapEntries = Map.ofEntries(Map.entry("apple", 1),Map.entry("banana", 2),Map.entry("orange", 3));System.out.println("Map (with entries): " + mapEntries);/*** 集合工厂方法创建的集合对象是不可变的,即不能修改它们的内容。* 如果尝试进行添加、删除或修改操作,将抛出UnsupportedOperationException异常。* 这有助于确保集合对象的内容保持不变,提高代码的安全性和可靠性。*/// Immutable object is modified: java.lang.UnsupportedOperationException// mapEntries.put("fruit", 0);}
}
完整代码案例地址
Java9 - 集合工厂方法