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. How to swap two elements in an ArrayList
  2. Java – Convert Vector to List example
  3. Java ArrayList of Object Sort Example (Comparable And Comparator)
  4. Comparator Interface in Java
  5. PriorityQueue Interface in Java Collections
  6. Java Iterator with examples

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 – 2021 BeginnersBook . Privacy Policy . Sitemap