Java的9带来了类似的方法:
List#of,
Set#of,
Map#of与几个重载方法,以避免调用可变参数之一。在情况下
Map,对于可变参数,你必须使用
Map#ofEntries。
在Java 9之前的版本中,您必须
Arrays#asList用作初始化
List和的入口点
Set:
List<String> list = Arrays.asList("hello", "world");Set<String> set = new HashSet<>(Arrays.asList("hello", "world"));如果您希望自己
Set是不可变的,则必须将其包装在的不可变集合中
Collections#unmodifiableSet:
Set<String> set = Collections.unmodifiableSet( new HashSet<>(Arrays.asList("hello", "world")));对于Map,您可以使用技巧创建匿名类,以扩展
Map实现,然后将其包装在中
Collections#unmodifiableMap。例:
Map<String, String> map = Collections.unmodifiableMap( //since it's an anonymous class, it cannot infer the //types from the content new HashMap<String, String>() {{ put.("hello", "world"); }}) );


