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 element at specific index in LinkedList example

By Chaitanya Singh | Filed Under: Java Collections

In this tutorial we will learn how to add a new element at specific index in LinkedList. We will be using add(int index, Element E) method of LinkedList class to perform this operation.

More about this method from javadoc:
public void add(int index, E element): Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

Example

In this example we have a LinkedList of Strings and we are adding an element to its 5th position(4th index) using add() method. The complete code is as follows:

import java.util.LinkedList;
import java.util.Iterator;
public class AddElement {
 
 public static void main(String[] args) {
 
    // Create a LinkedList
    LinkedList<String> linkedlist = new LinkedList<String>();
 
    // Add elements to LinkedList
    linkedlist.add("Delhi");
    linkedlist.add("Agra");
    linkedlist.add("Mysore");
    linkedlist.add("Chennai");
    linkedlist.add("Pune");
 
    // Adding new Element at 5th Position 
    linkedlist.add(4, "NEW ELEMENT");

    // Iterating the list in forward direction
    System.out.println("LinkedList elements After Addition:");
    Iterator it= linkedlist.iterator();
    while(it.hasNext()){
       System.out.println(it.next());
    }
 }
}

Output:

LinkedList elements After Addition:
Delhi
Agra
Mysore
Chennai
NEW ELEMENT
Pune

Enjoyed this post? Try these related posts

  1. Java ArrayList indexOf() Method example
  2. Hashtable in java with example
  3. Java – Remove all mappings from HashMap example
  4. Java – Remove first and last element from LinkedList example
  5. Java ArrayList lastIndexOf(Object 0bj) Method example
  6. Java – Search elements in LinkedList 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 – 2021 BeginnersBook . Privacy Policy . Sitemap