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
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java – Remove element from a specific index in LinkedList example

By Chaitanya Singh | Filed Under: Java Collections

In this example, we are gonna see how to remove an element from LinkedList.

Example

We will be using remove(int index) method of LinkedList class to remove an element from a specific index. Method definition and description are as follows:

public E remove(int index): Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the list.

import java.util.LinkedList;
public class RemoveFromLinkedList {
 
 public static void main(String[] args) {
 
    // Create a LinkedList
    LinkedList<String> linkedlist = new LinkedList<String>();
 
    // Add elements to LinkedList
    linkedlist.add("Cobol");
    linkedlist.add("JCL");
    linkedlist.add("C++");
    linkedlist.add("C#");
    linkedlist.add("Java");
 
    // Displaying Elements before replace
    System.out.println("LinkedList Elements:");
    for(String str: linkedlist){
       System.out.println(str);
    }
 
    // Removing 3rd element
    Object e1 = linkedlist.remove(2);
    System.out.println("\nElement "+ e1+ " removed from the list\n");

    // LinkedList elements after remove
    System.out.println("After removal:");
    for(String str2: linkedlist){
       System.out.println(str2);
    }
 }
}

Output:

LinkedList Elements:
Cobol
JCL
C++
C#
Java

Element C++ removed from the list

After removal:
Cobol
JCL
C#
Java

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