向List集合批量添加元素
1
2
|
List<String> list = new ArrayList<String>(); Collections.addAll(list, "a" , "b" , "c" ); |
或
1
2
3
|
String [] array = new String[] { "a" , "b" , "c" }; List<String> list = new ArrayList<String>(); Collections.addAll(list, array); |
或初始化时添加
1
2
3
4
5
6
7
|
List<String> list = new ArrayList<String>(){ { this .add( "a" ); this .add( "b" ); this .add( "c" ); } }; |
往集合中添加多个元素
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
/* - java.utils.Collections是集合工具类,用来对集合进行操作。部分方法如下: - public static <T> boolean addAll(Collection<T> c, T... elements):往集合中添加一些元素。 - public static void shuffle(List<?> list) 打乱顺序:打乱集合顺序。 */ public class Demo01Collections { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); //往集合中添加多个元素 /*list.add("a"); list.add("b"); list.add("c"); list.add("d"); list.add("e");*/ //public static <T> boolean addAll(Collection<T> c, T... elements):往集合中添加一些元素。 Collections.addAll(list, "a" , "b" , "c" , "d" , "e" ); System.out.println(list); //[a, b, c, d, e] //public static void shuffle(List<?> list) 打乱顺序:打乱集合顺序。 Collections.shuffle(list); System.out.println(list); //[b, d, c, a, e], [b, d, c, a, e] } } |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qq_41089622/article/details/103880508