Java教程

Java Collections addAll()

addAll()是Java Collections 类的一种方法,它将所有指定的元素添加到指定的集合中。要添加的元素可以单独指定,也可以指定为数组。

语法

以下是 addAll()方法的声明:
public static <T> boolean addAll(Collection<? super T> c, T... elements)

参数

参数 说明 必需/可选
c 这是一个要在其中插入元素的集合。 必需
elements 元素是要插入到c中的元素。 必需

返回

如果集合由于以下原因而更改,则 addAll()方法将返回 true 。方法调用。

异常

UnsupportedOperationException -如果集合c不支持添加操作。
NullPointerException -如果元素包含空值并且c不允许为空元素,或者c或元素为空。
IllegalArgumentException -如果a的某些属性

兼容版本

Java 1.5及更高版本

示例1

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class CollectionsAddAllExample1 {
  public static void main(String[] args) {
    Set<Integer> set = new HashSet<>();
            boolean b = Collections.addAll(set, 1, 2, 3, 4, 5);
            System.out.println("Boolean Result: "+b);
            System.out.println("Collection Value: "+set);    
        }
}
输出:
Boolean Result: true
Collection Value: [1, 2, 3, 4, 5]

示例2

import java.util.*;
public class CollectionsAddAllExample2 {
  public static void main(String[] args) {
    List<String> alist = new ArrayList<String>();
    alist.add("Rahul");
    alist.add("Karthik");
    alist.add("OM");
    alist.add("Shiva");
    alist.add("Anand");
    alist.add("Prem");
    System.out.println("The List are: "+alist);
    boolean b = Collections.addAll(alist, "Rahul", "OM", "Prem");
    System.out.println("Boolean Result: "+b);
    System.out.println("Collection Value: "+alist);
      }
}
输出:
The List are: [Rahul, Karthik, OM, Shiva, Anand, Prem]
Boolean Result: true
Collection Value: [Rahul, Karthik, OM, Shiva, Anand, Prem, Rahul, OM, Prem]

示例3

import java.util.*;
public class CollectionsAddAllExample3 {
  public static void main(String[] args) {
        List<String> alist = new ArrayList<String>();
        //Add values to the list
        alist.add("lidihuo");
        alist.add("SSSIT.COM");
        alist.add("Hindi100.COM");  
        System.out.println("Initial collection value: "+alist);
        //Add values to this collection and print final collection Result
        boolean b = Collections.addAll(alist, "Rank1","Rank2","Rank3");
        System.out.println("Boolean Result: "+b);
        System.out.println("final collection value: "+alist);
      }
}
输出:
Initial collection value: [lidihuo, SSSIT.COM, Hindi100.COM]
Boolean Result: true
final collection value: [lidihuo, SSSIT.COM, Hindi100.COM, Rank1, Rank2, Rank3]

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4