在Java 9中,Collections API添加了几个工厂方法。通过使用这些工厂方法,我们可以创建不可修改的 列表、集合和映射集合对象,从而减少代码行数。在Java 9中,List.of()、Set.of()、Map.of() 和Map.ofEntries()是提供方便的静态工厂方法,用于创建不可变的 集合。
List.of(elements...) Set.of(elements...) Map.of(k1, v1, k2, v2)
import java.util.Set; import java.util.List; import java.util.Map; public class ImmutableCollectionsTest { public static void main(String args[]) { List<String> stringList = List.of("a", "b", "c"); System.out.println("List values: " + stringList); Set<String> stringSet = Set.of("a", "b", "c"); System.out.println("Set values: " + stringSet); Map<String, Integer> stringMap = Map.of("a", 1, "b", 2, "c", 3); System.out.println("Map values: " + stringMap); } }
List values: [a, b, c] Set values: [a, b, c] Map values: {a=1, b=2, c=3}