當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java AbstractCollection addAll()用法及代碼示例


Java AbstractCollection 的 addAll(Collection C) 方法用於將提到的集合中的所有元素附加到此集合。元素是隨機添加的,不遵循任何特定順序。

用法:

boolean addAll(Collection C)

參數:參數 C 是要添加到集合中的任何類型的集合。

返回值:如果成功地將集合 C 的元素附加到現有集合,則該方法返回 true,否則返回 False。

以下示例程序旨在說明 AbstractCollection.addAll() 方法:



程序1:


// 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<String>
            abs1 = new TreeSet<String>();
  
        // 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<String>
            abs2 = new TreeSet<String>();
  
        // 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]

程序2:


// 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<Integer>
            abs1 = new TreeSet<Integer>();
  
        // 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<Integer>
            abs2 = new TreeSet<Integer>();
  
        // 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]




相關用法


注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 AbstractCollection addAll() Method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。