Add elements at beginning and end of LinkedList - Java Collection Framework

Java examples for Collection Framework:LinkedList

Introduction

To add an element at the beginning of the LinkedList, use void addFirst(Object obj) method.

To append an element at end of the LinkedList, use void addLast(Object obj) method.

Demo Code

 
import java.util.LinkedList;
 
public class Main {
 
  public static void main(String[] args) {
    LinkedList lList = new LinkedList();
   /*  w  w w  .j  av  a 2 s .c o  m*/
    //add elements to LinkedList
    lList.add("1");
    lList.add("2");
    lList.add("3");
    lList.add("4");
    lList.add("5");
   
    System.out.println("LinkedList contains : " + lList);
   
   
    lList.addFirst("0");
    System.out.println("After inserting 0 at beginning, LinkedList contains :" + lList);
 
   
    lList.addLast("6");
    System.out.println("After appending 0 at end, LinkedList contains :" + lList);
 
  }
}
 

Result


Related Tutorials