List.of和Arrays.asList有什么区别? [英] What is the difference between List.of and Arrays.asList?

查看:480
本文介绍了List.of和Arrays.asList有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 9引入了新的Collection Factory方法, List.of

Java 9 introduced new Collection Factory methods, List.of:

List<String> strings = List.of("first", "second");

那么,之前和新选项之间有什么区别?也就是说,它之间有什么区别:

So, what's the difference between the previous and the new options? That is, what's the difference between this:

Arrays.asList(1, 2, 3); 

这个:

List.of(1, 2, 3);


推荐答案

Arrays.asList 返回一个可变列表,而 List.of 返回的列表是不可变的:

Arrays.asList returns a mutable list while the list returned by List.of is immutable:

List<Integer> list = Arrays.asList(1, 2, null);
list.set(1, 10); // OK

List<Integer> list = List.of(1, 2, 3);
list.set(1, 10); // Fails

Arrays.asList 允许null元素 List.of 不:

Arrays.asList allows null elements while List.of doesn't:

List<Integer> list = Arrays.asList(1, 2, null); // OK
List<Integer> list = List.of(1, 2, null); // Fails with a NullPointerException

包含方法行为与空值不同:

contains method behaves differently with nulls:

List<Integer> list = Arrays.asList(1, 2, 3);
list.contains(null); // Return false

List<Integer> list = List.of(1, 2, 3);
list.contains(null); // Throws NullPointerException

Arrays.asList 返回传递数组的视图,因此对数组的更改也将反映在列表中。对于 List.of ,这不是真的:

Arrays.asList returns a view of the passed array, so the changes to the array will be reflected in the list too. For List.of this is not true:

Integer[] array = {1,2,3};
List<Integer> list = Arrays.asList(array);
array[1] = 10;
System.out.println(list); // Prints [1, 10, 3]

Integer[] array = {1,2,3};
List<Integer> list = List.of(array);
array[1] = 10;
System.out.println(list); // Prints [1, 2, 3]    

这篇关于List.of和Arrays.asList有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆