In this post we will see how to add elements in LinkedList.
Elements can be added to LinkedList either using add(E e) which adds elements at the end of the list OR add(int index, E element) which adds elements to a specified position.
Note that index parameter starts from 0. So if you want to add element to the 2nd position then index will be 1.
Lets see an example using both the methods
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package com.kscodes.collections.linkedList; import java.util.LinkedList; public class LinkedListAddElement { public static void main(String[] args) { LinkedList<String> linkedList = new LinkedList<>(); // Use add(E e) to add elements linkedList.add("First Element"); linkedList.add("Second Element"); linkedList.add("Third Element"); linkedList.add("Fourth Element"); // now use add(int index, E element) to add element in the second // position. Note that index parameter starts from 0. So if you want to // add element to the 2nd position then index will be 1 linkedList.add(1, "I am between One and Two"); // Lets print the elements to confirm for (String element : linkedList) { System.out.println(element); } } } |
Output
1 2 3 4 5 |
First Element I am between One and Two Second Element Third Element Fourth Element |
We can add elements to Linked List using addFirst and addLast methods as well.
You can get more details here – addFirst and addLast methods in LinkedList