11
10

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 5 years have passed since last update.

指定サイズ分固定値で埋めたListの生成方法

Last updated at Posted at 2015-04-03

指定サイズ(実行ごとに数は可変)分固定値で埋めたListを作りたい、と思った時に普通に

int num = 5;

String[] arr = new String[num];
Arrays.fill(arr, "TEST");
List<String> lst = Arrays.asList(arr);

System.out.println(lst);
// [TEST, TEST, TEST, TEST, TEST]

だと3stepも書かなければいけないので別アプローチから

int num = 5;

List<String> lst = Arrays.asList(new String[num]);
Collections.fill(lst, "TEST");

System.out.println(lst);
// [TEST, TEST, TEST, TEST, TEST]

としても2step。
なんで1stepで書けないんだと調べていたらCollections#nCopies(int, T)なる何このメソッド名的なメソッドが大昔(J2SE 1.2)からあって

int num = 5;

List<String> lst = Collections.nCopies(num, "TEST");

System.out.println(lst);
// [TEST, TEST, TEST, TEST, TEST]

ああ、できた、というメモ。

ちなみにCollections#nCopies(int, T)は不変のリストを返却するので、作成したリストにさらに追加等の処理を行う場合は

int num = 5;

List<String> lst = new ArrayList<>(Collections.nCopies(num, "TEST"));

lst.add("ABC");
System.out.println(lst);
// [TEST, TEST, TEST, TEST, TEST, ABC]

とする。
※コードはjava 7で書いています

11
10
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
11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?