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

【Java】配列からListへの変換

Last updated at Posted at 2019-08-11

配列からListへ変換をしたい

public static void main(String[] args) {
				
	String arr[] = {"orange","apple","cherry","melon","grape"};
	List<String> list = Arrays.asList(arr);

arrを引数にしたArrays.asListをlistに代入

###要素数を追加したい場合

####NG例

	List<String> list = Arrays.asList(arr);
	list.add("banana");

(原因)Arrays.asList()は追加や削除といったListのメソッドの操作を受け付けない

####OK例

	List<String> list = Arrays.asList(arr);
	List<String> list2 = new ArrayList<>(list);
	list2.add("banana");

listをArrayListの引数にしてlist2に代入
上記を簡潔に書くと

	List<String> list = new ArrayList<>(Arrays.asList(arr));
	list.add("banana");
3
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
3
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?