Java SortedSet addAll()方法及示例
addAll(Collection C) 方法用于将所述集合中的所有元素追加到现有集合中。这些元素是随机添加的,不遵循任何特定的顺序。
语法
boolean addAll(Collection C)
参数: 参数C是一个要添加到集合中的任何类型的集合。
返回值: 如果该方法成功地将集合C的元素添加到这个Set中,则返回 true ,否则返回False。
注意 :SortedSet中的addAll()方法是继承自Java中的Set接口。
下面的程序说明了Java.util.Set.addAll()方法。
程序1: 追加一个树形集合。
// Java code to illustrate addAll() import java.io.*;import java.util.*; public class TreeSetDemo { public static void main(String args[]) { // Creating an empty Set SortedSet<String> st1 = new TreeSet<String>(); // Use add() method to add // elements into the Set st1.add("Welcome"); st1.add("To"); st1.add("Geeks"); st1.add("4"); st1.add("Geeks"); st1.add("TreeSet"); // Displaying the Set System.out.println("Set: " + st1); // Creating another Set Set<String> st2 = new TreeSet<String>(); // Use add() method to add // elements into the Set st2.add("Hello"); st2.add("World"); // Using addAll() method to Append st1.addAll(st2); // Displaying the final Set System.out.println("Set: " + st1); }}
输出:
Set: [4, Geeks, To, TreeSet, Welcome]Set: [4, Geeks, Hello, To, TreeSet, Welcome, World]
程序2: 追加一个数组列表。
// Java code to illustrate addAll() import java.io.*;import java.util.*; public class SetDemo { public static void main(String args[]) { // Creating an empty Set SortedSet<String> st1 = new TreeSet<String>(); // Use add() method to // add elements into the Set st1.add("Welcome"); st1.add("To"); st1.add("Geeks"); st1.add("4"); st1.add("Geeks"); st1.add("Set"); // Displaying the Set System.out.println("Initial Set: " + st1); // An array collection is created ArrayList<String> collect = new ArrayList<String>(); collect.add("A"); collect.add("Computer"); collect.add("Portal"); // Using addAll() method to Append st1.addAll(collect); // Displaying the final Set System.out.println("Final Set: " + st1); }}输出:
Initial Set: [4, Geeks, Set, To, Welcome]Final Set: [4, A, Computer, Geeks, Portal, Set, To, Welcome]
参考资料 : https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#addAll(java.util.Collection)
