List.of と Arrays.asList の違いは何ですか? 質問する

List.of と Arrays.asList の違いは何ですか? 質問する

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.asListnull 要素は許可されますが、List.of許可されません。

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

containsnull の場合は動作が異なります。

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]

おすすめ記事