Example
In this example we will learn how to add elements at the beginning and end of a LinkedList. We will be using addFirst() and addLast() method of LinkedList class. Method definition and description are as follows:
1) public void addFirst(E e)
: Inserts the specified element at the beginning of this list.
2) public void addLast(E e)
: Appends the specified element to the end of this list.
Complete Code:
import java.util.LinkedList; public class AddExample { public static void main(String[] args) { // Creating LinkedList of String Elements LinkedList<String> linkedlist = new LinkedList<String>(); //Populating it with String values linkedlist.add("AA"); linkedlist.add("BB"); linkedlist.add("CC"); linkedlist.add("DD"); linkedlist.add("EE"); //Displaying LinkedList elements System.out.println(linkedlist); //Adding an element at the beginning linkedlist.addFirst("FIRST"); //Displaying the List after addition System.out.println(linkedlist); //Adding an element at the end of list linkedlist.addLast("LAST"); //Displaying the final list System.out.println(linkedlist); } }
Output:
[AA, BB, CC, DD, EE] [FIRST, AA, BB, CC, DD, EE] [FIRST, AA, BB, CC, DD, EE, LAST]
Leave a Reply