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


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


java.util.TreeSet.addAll(Collection C)方法用於將上述集合中的所有元素附加到現有集合中。元素是隨機添加的,無需遵循任何特定順序。
用法:

boolean addAll(Collection C)

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

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


以下示例程序旨在說明Java.util.TreeSet.addAll()方法:
示例1:附加樹集。

// Java code to illustrate addAll() 
import java.io.*; 
import java.util.TreeSet; 
  
public class TreeSetDemo { 
    public static void main(String args[]) 
    { 
        // Creating an empty TreeSet 
        TreeSet<String> tree = new TreeSet<String>(); 
  
        // Use add() method to add elements into the Set 
        tree.add("Welcome"); 
        tree.add("To"); 
        tree.add("Geeks"); 
        tree.add("4"); 
        tree.add("Geeks"); 
        tree.add("TreeSet"); 
  
        // Displaying the TreeSet 
        System.out.println("TreeSet: " + tree); 
  
        // Creating anothe TreeSet 
        TreeSet<String> tree_two = new TreeSet<String>(); 
  
        // Use add() method to add elements into the Set 
        tree_two.add("Hello"); 
        tree_two.add("World"); 
  
        // Using addAll() method to Append 
        tree.addAll(tree_two); 
  
        // Displaying the final tree 
        System.out.println("TreeSet: " + tree); 
    } 
}
輸出:
TreeSet: [4, Geeks, To, TreeSet, Welcome]
TreeSet: [4, Geeks, Hello, To, TreeSet, Welcome, World]

示例2:附加一個ArrayList。

// Java code to illustrate addAll() 
import java.io.*; 
import java.util.TreeSet; 
import java.util.ArrayList; 
  
public class TreeSetDemo { 
    public static void main(String args[]) 
    { 
        // Creating an empty TreeSet 
        TreeSet<String> tree = new TreeSet<String>(); 
  
        // Use add() method to add elements into the Set 
        tree.add("Welcome"); 
        tree.add("To"); 
        tree.add("Geeks"); 
        tree.add("4"); 
        tree.add("Geeks"); 
        tree.add("TreeSet"); 
  
        // Displaying the TreeSet 
        System.out.println("TreeSet: " + tree); 
  
        // 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 
        tree.addAll(collect); 
  
        // Displaying the final tree 
        System.out.println("Final TreeSet: " + tree); 
    } 
}
輸出:
TreeSet: [4, Geeks, To, TreeSet, Welcome]
Final TreeSet: [4, A, Computer, Geeks, Portal, To, TreeSet, Welcome]


相關用法


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