Java LinkedList add() Method
Example
Add items from one list into another:
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> cars = new LinkedList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
LinkedList<String> brands = new LinkedList<String>();
brands.add("Microsoft");
brands.add("W3Schools");
brands.add("Apple");
brands.addAll(cars);
System.out.println(brands);
}
}
Definition and Usage
The addAll()
method adds all of the items from a collection to the list.
If an index is provided then the new items will be placed at the specified index, pushing all of the following elements in the list ahead.
If an index is not provided then the new items will be placed at the end of the list.
Syntax
One of the following:
public boolean addAll(Collection<T> items)
public boolean addAll(int index, Collection<T> items)
T
refers to the data type of items in the list.
Parameter Values
Parameter | Description |
---|---|
index | Optional. The position in the list at which to add the items. |
items | Required. A collection containing items to be added to the list. |
Technical Details
Returns: | true if the list changed and false otherwise. |
---|---|
Throws: |
IndexOutOfBoundsException - If the index is less than zero or greater than the size of the list.NullPointerException - If the collection is null.
|
More Examples
Example
Add items at a specified position in the list:
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> cars = new LinkedList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
LinkedList<String> brands = new LinkedList<String>();
brands.add("Microsoft");
brands.add("W3Schools");
brands.add("Apple");
brands.addAll(1, cars);
System.out.println(brands);
}
}
Related Pages
❮ LinkedList Methods