• Tags
  •         
  • www.breakyizhan.com
  •    

    所述java.util.TreeSet.addAll(Collection C)方法用于所有从提到集合的元素的追加到现有组。这些元素是随机添加的,不遵循任何特定顺序。
    句法:

    boolean addAll(Collection C)

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

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

    下面的程序说明了Java.util.TreeSet.addAll()方法:

    程序1:附加TreeSet。

    // 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]

     
    转载请保留页面地址:https://www.breakyizhan.com/java/4919.html