溫馨提示×

java給list賦值的方法是什么

小億
182
2023-12-08 17:39:42
欄目: 編程語言

Java中給List賦值的方法有以下幾種:

  1. 使用add()方法逐個(gè)添加元素:
List<String> list = new ArrayList<>();
list.add("元素1");
list.add("元素2");
list.add("元素3");
  1. 使用數(shù)組初始化List:
String[] array = {"元素1", "元素2", "元素3"};
List<String> list = Arrays.asList(array);
  1. 使用Collections工具類的addAll()方法將另一個(gè)Collection中的元素添加到List中:
List<String> list = new ArrayList<>();
Collection<String> collection = new ArrayList<>();
collection.add("元素1");
collection.add("元素2");
collection.add("元素3");
Collections.addAll(list, collection);
  1. 使用Collections工具類的nCopies()方法創(chuàng)建指定數(shù)量的相同元素,并賦值給List:
List<String> list = new ArrayList<>(Collections.nCopies(3, "元素"));

以上是常用的給List賦值的方法,根據(jù)具體需求選擇合適的方法進(jìn)行賦值操作。

0