beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java – Add elements at beginning and end of LinkedList example

By Chaitanya Singh | Filed Under: Java Collections

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]

Enjoyed this post? Try these related posts

  1. HashSet Class in Java with example
  2. How to get the size of TreeMap example – Java
  3. How to sort HashMap in Java by Keys and Values
  4. Vector Iterator example in Java
  5. Java – Get sub List from LinkedList example
  6. Java ArrayList indexOf() Method example

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

  • Java Tutorial
  • OOPs Concepts

Java Collections

  • ArrayList
  • LinkedList
  • ArrayList vs LinkedList
  • Vector
  • ArrayList vs Vector
  • HashMap
  • TreeMap
  • LinkedHashMap
  • HashSet
  • TreeSet
  • LinkedHashSet
  • Hashtable
  • HashMap vs Hashtable
  • Queue
  • PriorityQueue
  • Deque & ArrayDeque
  • Iterator
  • ListIterator
  • Comparable Interface
  • Comparator Interface
  • Java Collections Interview Q

MORE ...

  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2019 BeginnersBook . Privacy Policy . Sitemap