Java Collections addAll()

addAll() 是Java Collections类的方法,用于所有指定元素添加到指定的集合。

1 语法

public static <T> boolean addAll(Collection<? super T> c, T... elements)  

2 参数

c:需要添加的集合。

elements:需要添加的元素。

3 返回值

该方法调用返回true,如果集合更改为调用的结果

4 Collections addAll()示例1

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.addAll的例子
 */
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class Demo {

    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]

5 Collections addAll()示例2

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.addAll的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        List<String> alist = new ArrayList<String>();
        alist.add("Eric");
        alist.add("Jack");
        alist.add("Lucy");
        alist.add("Rose");
        alist.add("Paul");
        alist.add("Mark");
        System.out.println("The List are: "+alist);
        boolean b = Collections.addAll(alist, "Eric", "Lucy", "Mark");
        System.out.println("Boolean Result: "+b);
        System.out.println("Collection Value: "+alist);
    }
}

输出结果为:

The List are: [Eric, Jack, Lucy, Rose, Paul, Mark]
Boolean Result: true
Collection Value: [Eric, Jack, Lucy, Rose, Paul, Mark, Eric, Lucy, Mark]

6 Collections addAll()示例3

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.addAll的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        //创建ArrayList
        List<String> alist = new ArrayList<String>();
        //添加元素
        alist.add("Yiidian.com");
        alist.add("Baidu.com");
        alist.add("Google.com");
        System.out.println("Initial collection value: "+alist);
        boolean b = Collections.addAll(alist, "Rank1","Rank2","Rank3");
        System.out.println("Boolean Result: "+b);
        System.out.println("Final collection value: "+alist);
    }
}

输出结果为:

Initial collection value: [Yiidian.com, Baidu.com, Google.com]
Boolean Result: true
Final collection value: [Yiidian.com, Baidu.com, Google.com, Rank1, Rank2, Rank3]

 

热门文章

优秀文章