共計 603 個字符,預計需要花費 2 分鐘才能閱讀完成。
Java 中給 List 賦值的方法有以下幾種:
- 使用 add() 方法逐個添加元素:
List<String> list = new ArrayList<>();
list.add(" 元素 1 ");
list.add(" 元素 2 ");
list.add(" 元素 3 ");
- 使用數組初始化 List:
String[] array = {" 元素 1 ", " 元素 2 ", " 元素 3 "};
List<String> list = Arrays.asList(array);
- 使用 Collections 工具類的 addAll() 方法將另一個 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);
- 使用 Collections 工具類的 nCopies() 方法創建指定數量的相同元素,并賦值給 List:
List<String> list = new ArrayList<>(Collections.nCopies(3, " 元素 "));
以上是常用的給 List 賦值的方法,根據具體需求選擇合適的方法進行賦值操作。
丸趣 TV 網 – 提供最優質的資源集合!
正文完