Java 9ではリスト用の新しいファクトリーメソッドが導入されました。List.of
:
List<String> strings = List.of("first", "second");
以前のオプションと新しいオプションの違いは何でしょうか? つまり、次の違いは何でしょうか:
Arrays.asList(1, 2, 3);
この:
List.of(1, 2, 3);
ベストアンサー1
Arrays.asList
は可変リストを返しますが、 が返すリストはList.of
構造的に不変:
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 with UnsupportedOperationException
Arrays.asList
null 要素は許可されますが、List.of
許可されません。
List<Integer> list = Arrays.asList(1, 2, null); // OK
List<Integer> list = List.of(1, 2, null); // Fails with NullPointerException
contains
null の場合は動作が異なります。
List<Integer> list = Arrays.asList(1, 2, 3);
list.contains(null); // Returns false
List<Integer> list = List.of(1, 2, 3);
list.contains(null); // Fails with NullPointerException
Arrays.asList
渡された配列のビューを返すので、配列への変更はリストにも反映されます。List.of
これは正しくありません。
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]