📌  相关文章
📜  Java中的 AbstractCollection addAll() 方法及示例

📅  最后修改于: 2022-05-13 01:54:44.874000             🧑  作者: Mango

Java中的 AbstractCollection addAll() 方法及示例

Java AbstractCollectionaddAll( Collection C )方法用于将提到的集合中的所有元素附加到此集合。元素是随机添加的,不遵循任何特定顺序。

句法:

boolean addAll(Collection C)

参数:参数C是要添加到集合中的任何类型的集合。

返回值:如果成功地将集合C的元素附加到现有集合,则该方法返回 true,否则返回 False。

下面的程序说明了 AbstractCollection.addAll() 方法:

方案一:

// Java code to illustrate addAll()
// method of AbstractCollection
  
import java.util.*;
import java.util.AbstractCollection;
  
public class AbstractCollectionDemo {
    public static void main(String args[])
    {
  
        // Creating an empty collection
        AbstractCollection
            abs1 = new TreeSet();
  
        // Use add() method to add
        // elements into the Collection
        abs1.add("Welcome");
        abs1.add("To");
        abs1.add("Geeks");
        abs1.add("4");
        abs1.add("Geeks");
        abs1.add("TreeSet");
  
        // Displaying the Collection
        System.out.println("AbstractCollection 1: "
                           + abs1);
  
        // Creating anothe Collection
        AbstractCollection
            abs2 = new TreeSet();
  
        // Displaying the Collection
        System.out.println("AbstractCollection 2: "
                           + abs2);
  
        // Using addAll() method to Append
        abs2.addAll(abs1);
  
        // Displaying the Collection
        System.out.println("AbstractCollection 2: "
                           + abs2);
    }
}
输出:
AbstractCollection 1: [4, Geeks, To, TreeSet, Welcome]
AbstractCollection 2: []
AbstractCollection 2: [4, Geeks, To, TreeSet, Welcome]

方案二:

// Java code to illustrate addAll()
// method of AbstractCollection
  
import java.util.*;
import java.util.AbstractCollection;
  
public class AbstractCollectionDemo {
    public static void main(String args[])
    {
  
        // Creating an empty collection
        AbstractCollection
            abs1 = new TreeSet();
  
        // Use add() method to add
        // elements into the Collection
        abs1.add(10);
        abs1.add(20);
        abs1.add(30);
        abs1.add(40);
        abs1.add(50);
  
        // Displaying the Collection
        System.out.println("AbstractCollection 1: "
                           + abs1);
  
        // Creating anothe Collection
        AbstractCollection
            abs2 = new TreeSet();
  
        // Displaying the Collection
        System.out.println("AbstractCollection 2: "
                           + abs2);
  
        // Using addAll() method to Append
        abs2.addAll(abs1);
  
        // Displaying the Collection
        System.out.println("AbstractCollection 2: "
                           + abs2);
    }
}
输出:
AbstractCollection 1: [10, 20, 30, 40, 50]
AbstractCollection 2: []
AbstractCollection 2: [10, 20, 30, 40, 50]