Apart from add(E e) and add(int index, E element) methods, we have addFirst and addLast methods in LinkedList to add elements.
1. addFirst(E e) – Inserts the specified element at the beginning of this list.
2. addLast(E e) – Appends the specified element to the end of this list.
Example : addFirst and addLast methods in LinkedList
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 28 29 30 31 32 33 |
package com.kscodes.collections.linkedList; import java.util.LinkedList; public class LinkedListAddFirstLast { public static void main(String[] args) { LinkedList<String> linkedList = new LinkedList<>(); // Use add(E e) to add elements linkedList.add("Java"); linkedList.add("JSP"); linkedList.add("Spring MVC"); linkedList.add("Hibernate"); linkedList.add("Oracle"); System.out.println("We have a Linked List with Elements::" + linkedList.toString()); // Lets use addFirst(E e) to add element "Coding" at the beginning of // the linkedList linkedList.addFirst("Coding"); // Now Lets use addLast(E e) to add element "Programming" at the end of // the linkedList linkedList.addLast("Programming"); System.out.println("Now the Linked List has Elements::" + linkedList.toString()); } } |
Output
1 2 |
We have a Linked List with Elements::[Java, JSP, Spring MVC, Hibernate, Oracle] Now the Linked List has Elements::[Coding, Java, JSP, Spring MVC, Hibernate, Oracle, Programming] |