1
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?

More than 1 year has passed since last update.

Javaで初期値を設定したListの作り方

Last updated at Posted at 2022-08-20

概要

JavaでListを作成する際に、1行で書く方法のまとめ。
いつも忘れちゃうので。

基本的な初期化

キホンのキです。new してaddする。

import java.util.ArrayList;
import java.util.List;

public class Sample {

    public static void main(String args[]) {

        List<String> list0 = new ArrayList<String>();
        list0.add("a");
        list0.add("b");
        for(String x : list0) System.out.println(x);
}

初期値込みで1行で書く方法

以下3つ例示します。
(1) List.of
(2) Arrays.asList
(3) arrayListとArrays.asList の併用

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Sample {

    public static void main(String args[]) {

        List<String> list1 = List.of("a", "b", "c");
        for(String x : list1) System.out.println(x);

        List<String> list2 = Arrays.asList("a", "b", "c");
        for(String x : list2) System.out.println(x);

        List<String> list3 = new ArrayList<String>(Arrays.asList("a", "b", "c"));
        for(String x : list3) System.out.println(x);
    }
}

要素が一つだけなら、こんな書き方も。

import java.util.Collections;
import java.util.List;

public class Sample {

    public static void main(String args[]) {

        List<String> list4 = Collections.singletonList("a");
        for(String x : list4) System.out.println(x);

    }
}
1
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
1
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?