0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Javaでの List.of() と Arrays.asList() の違い

0
Posted at

Javaでリストを簡単に作成する方法としてよく使われるのが、Arrays.asList() と List.of() です。両者は似ていますが、動作や制約が異なります。

基本的な使い方

import java.util.*;

public class Main {
    public static void main(String[] args) {
        // Arrays.asList()
        List<String> list1 = Arrays.asList("a", "b", "c");
        System.out.println(list1); // [a, b, c]

        // List.of()
        List<String> list2 = List.of("a", "b", "c");
        System.out.println(list2); // [a, b, c]
    }
}

どちらも固定の要素でリストを作ることができます。

変更可能かどうか

特性 Arrays.asList() List.of()
要素の変更 可能 (set は OK) 不可 (UnsupportedOperationException)
要素の追加/削除 不可 (add/remove は例外) 不可 (add/remove は例外)
List<String> list1 = Arrays.asList("a", "b");
list1.set(0, "x"); // OK
list1.add("c"); // Exception

List<String> list2 = List.of("a", "b");
list2.set(0, "x"); // Exception

Arrays.asList() は「サイズ固定」ですが、要素の変更は可能です。
List.of() は完全に不変(immutable)です。

nullの扱い

Arrays.asList():nullを要素にすることが可能
List.of():nullを含めると NullPointerException が発生

List<String> list1 = Arrays.asList("a", null); // OK
List<String> list2 = List.of("a", null);      // NullPointerException

型と可変性の違い

Arrays.asList() は 固定長の配列をラップしたList を返す
→ 元の配列を変更するとリストも変化します。

String[] array = {"a", "b"};
List<String> list = Arrays.asList(array);
array[0] = "x";
System.out.println(list); // [x, b]

List.of() は 新しい不変のList を返す
→ 元の配列に影響されません。

String[] array = {"a", "b"};
List<String> list = List.of(array);
array[0] = "x";
System.out.println(list); // [a, b]

まとめ

特徴 Arrays.asList() List.of()
変更(set) 可能 不可
サイズ変更(add/remove) 不可 不可
nullを許容 不可
元配列の影響 あり なし
JDK 全て(1.2〜) 9以降
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?