Java中的LinkedList addAll()方法

  1. JAVAutil。LinkedList。addAll(集合C) :此方法用于将作为参数传递给此函数的集合中的所有元素附加到列表末尾,同时记住集合迭代器的返回顺序。

    语法:

    boolean addAll(Collection C)

    参数: 参数 C 是ArrayList的集合。它是需要将其元素追加到列表末尾的集合。

    返回值: 如果至少执行了一个append操作,则该方法返回true。

    下面的程序演示了Java。util。LinkedList。addAll()方法:

    // Java code to illustrate boolean addAll()
    import java.util.*;
    import java.util.LinkedList;
    import java.util.ArrayList;
    public class LinkedListDemo {
    public static void main(String args[]) {
    // Creating an empty LinkedList
    LinkedList<String> list = new LinkedList<String>();
    // Use add() method to add elements in the list
    list.add( "Geeks" );
    list.add( "for" );
    list.add( "Geeks" );
    list.add( "10" );
    list.add( "20" );
    // A collection is created
    Collection<String> collect = new ArrayList<String>();
    collect.add( "A" );
    collect.add( "Computer" );
    collect.add( "Portal" );
    collect.add( "for" );
    collect.add( "Geeks" );
    // Displaying the list
    System.out.println( "The LinkedList is: " + list);
    // Appending the collection to the list
    list.addAll(collect);
    // Clearing the list using clear() and displaying
    System.out.println( "The new linked list is: " + list);
    }
    }

    
    

    输出:

    The LinkedList is: [Geeks, for, Geeks, 10, 20]
    The new linked list is: [Geeks, for, Geeks, 10, 20, A, Computer, Portal, for, Geeks]
    

  2. JAVAutil。LinkedList。addAll(整数索引,集合C) :此方法用于将集合中作为参数传递给此函数的所有元素附加到列表的特定索引或位置。

    语法:

    boolean addAll(int index, Collection C)

    参数: 此函数接受两个参数,如上述语法所示,如下所述。

    • 指数 :此参数为整数数据类型,指定列表中从容器中的元素插入位置开始的位置。
    • C :这是ArrayList的集合。它是需要附加元素的集合。

    返回值: 如果至少执行了一个append操作,则该方法返回TRUE。

    下面的程序演示了Java。util。LinkedList。addAll()方法:

    // Java code to illustrate boolean addAll()
    import java.util.*;
    import java.util.LinkedList;
    import java.util.ArrayList;
    public class LinkedListDemo {
    public static void main(String args[]) {
    // Creating an empty LinkedList
    LinkedList<String> list = new LinkedList<String>();
    // Use add() method to add elements in the list
    list.add( "Geeks" );
    list.add( "for" );
    list.add( "Geeks" );
    list.add( "10" );
    list.add( "20" );
    // Creating a Collection
    Collection<String> collect = new ArrayList<String>();
    collect.add( "A" );
    collect.add( "Computer" );
    collect.add( "Portal" );
    collect.add( "for" );
    collect.add( "Geeks" );
    // Displaying the list
    System.out.println( "The LinkedList is: " + list);
    // Appending the collection to the list
    list.addAll( 1 , collect);
    // Clearing the list using clear() and displaying
    System.out.println( "The new linked list is: " + list);
    }
    }

    
    

    输出:

    The LinkedList is: [Geeks, for, Geeks, 10, 20]
    The new linked list is: [Geeks, A, Computer, Portal, for, Geeks, for, Geeks, 10, 20]
    

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享