目录
  • 向List集合批量添加元素
  • 往集合中添加多个元素

向List集合批量添加元素

List<String> list = new ArrayList<String>();
Collections.addAll(list, "a", "b", "c");

String [] array = new String[] {"a", "b", "c"};
List<String> list = new ArrayList<String>();
Collections.addAll(list, array);

或初始化时添加

		List<String> list = new ArrayList<String>(){
			{
				this.add("a");
				this.add("b");
				this.add("c");
			}
		};

往集合中添加多个元素

/*
    - 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]
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。 

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。