Add elements in LinkedList
We can use add() method of LinkedList to insert new elements to LinkedList
There are 6 overloaded “add” methods defined in LinkedList
1) boolean add(Object o);
2) void add(int index, Object o);
3) boolean addAll(Collection extends E> c);
4) boolean addAll(int index,Collection extends E> c);
5) void addFirst(Object o);
6) void addLast(Object o);
We have already discussed first 4 methods in the above list in the ArrayList article, and its same for LinkedList as well.
Please refer add-elements-in-arraylist article for the same
Let’s discuss last 2 methods with example
1) Void addFirst(Object o)
2) Void addLast(Object o)
addFirst : This method is used to add an element at the beginning of the list
addLast : This method is used to add an element at the end of the list
Example :
- import java.util.*;
- public class LinkedListAdd {
- public static void main(String[] args) {
- LinkedList<String> list = new LinkedList<String>();
- list.add("Java");
- list.add("c++");
- list.add("python");
- System.out.println("Linked list before performing add first and add last ");
- System.out.println(list);
- //Performing add first and add last
- list.addFirst("Hai");
- list.addLast("Bye");
- System.out.println("Linked list after performing add first and add last ");
- System.out.println(list);
- }
- }
import java.util.*; public class LinkedListAdd { public static void main(String[] args) { LinkedList<String> list = new LinkedList<String>(); list.add("Java"); list.add("c++"); list.add("python"); System.out.println("Linked list before performing add first and add last "); System.out.println(list); //Performing add first and add last list.addFirst("Hai"); list.addLast("Bye"); System.out.println("Linked list after performing add first and add last "); System.out.println(list); } }
We can see in the output that,
addFirst has added element at the beginning of the list
addLast has added element at the end of the list