用于简单的创建不可变的少量元素的集合,如:
public class Test{
public static void main(String[] args) {
Set<String> str1=Set.of("a","b","c");
//str1.add("c"); 这里在编译的时候不会错,但是执行的时候会报错,因为是不可变的
System.out.println(str1);
Map<String,Integer> str2=Map.of("a",1,"b",2);
System.out.println(str2);
List<String> str3=List.of("a","b");
System.out.println(str3);
}
}
- 只有Map、Set、List接口中有此类方法,HashMap、ArrayList中并没有此类方法
- 返回的集合是不可变集合