Java LinkedList addAll()方法
- java.util.LinkedList.addAll(Collection C) 。该方法用于将作为参数传递给该函数的集合中的所有元素追加到一个列表的末尾,同时牢记集合迭代器的返回顺序。
语法:
boolean addAll(Collection C)
参数:参数C是一个ArrayList的集合。它是一个集合,其元素需要被追加到列表的最后。
返回值:该方法如果至少执行了一个追加的动作,则返回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]
- java.util.LinkedList.addAll(int index, Collection C) 。该方法用于将作为参数传递给该函数的集合中的所有元素追加到一个列表的特定索引或位置。
语法:
boolean addAll(int index, Collection C)
参数:该函数接受两个参数,如上面的语法所示,描述如下。
- index: 这个参数是整数数据类型,指定了列表中的位置,从这个位置开始,容器中的元素将被插入。
- 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]
极客教程