CodesJava

Easy learning with example program codes

how to remove element from linkedlist in java?


LinkedList:

The LinkedList class extends AbstractSequentialList and implements the List and Deque interface. It uses linked list data structure to store elements. It can contain duplicate elements. It is not synchronized.

Note: It not provides the random access facility.

Following methods are used to remove element from linkedlist in java:

  • remove(): It retrieves and removes the first element of the list.
  • remove(index): It removes the element at the specified position in the list.
  • remove(object): It removes the first occurrence of the specified element from the list, if it is present.
  • removeFirst(): It removes and returns the first element from the list.
  • removeFirstOccurrence(object): It removes the first occurrence of the specified element in the list (when traversing the list from head to tail).
  • removeLast(): It removes and returns the last element from the list.
  • removeLastOccurrence(object): It removes the last occurrence of the specified element in the list (when traversing the list from head to tail).

Example:

package com.codesjava;
 
import java.util.LinkedList;
 
public class Test {
  public static void main(String args[]){
	LinkedList<String> linkedList = new LinkedList<String>();
	linkedList.add("Jai");
	linkedList.add("Mahesh");
	linkedList.add("Naren");
	linkedList.add("Vivek");
	linkedList.add("Vishal");
	linkedList.add("Hemant");
	System.out.println("Actual LinkedList:"+linkedList);
	System.out.println("remov() method:"+linkedList.remove());
        System.out.println("After remove() method call:");
        System.out.println(linkedList);
        System.out.println("remove(index) method:"+linkedList.remove(2));
        System.out.println("After remove(index) method call:");
        System.out.println(linkedList);
        System.out.println("remov(object) method:"+linkedList.remove("Hemant"));
        System.out.println("After remove(object) method call:" + linkedList);
  }
}

Output

Actual LinkedList:[Jai, Mahesh, Naren, Vivek, Vishal, Hemant]
remov() method:Jai
After remove() method call:
[Mahesh, Naren, Vivek, Vishal, Hemant]
remove(index) method:Vivek
After remove(index) method call:
[Mahesh, Naren, Vishal, Hemant]
remov(object) method:true
After remove(object) method call:[Mahesh, Naren, Vishal]
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki