Java - Remove Element From Specific Index In LinkedList
Chapter:
Data Structures
Last Updated:
28-08-2016 19:26:21 UTC
Program:
/* ............... START ............... */
import java.util.LinkedList;
public class JavaRemoveElementLinkedList {
public static void main(String[] args) {
// Create a LinkedList
LinkedList<String> linkedlist = new LinkedList<String>();
// Add elements to LinkedList
linkedlist.add("Cobol");
linkedlist.add("Java");
linkedlist.add("C++");
linkedlist.add("C#");
// 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);
}
}
}
/* ............... END ............... */
Output
LinkedList Elements:
Cobol
Java
C++
C#
Element C++ removed from the list
After removal:
Cobol
Java
C#
Notes:
-
remove(int index) method of LinkedList class to remove an element from a specific index.
- public 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.
Tags
Remove element from a specific index in LinkedList, Java, Data Structures