Sunday, 25 May 2014

LinkedList : remove(int index) : Removes the element at the specified position in this list.

public E remove(int index)
Removes the element at the specified position in this list. Shifts any subsequent elements to the left.

import java.util.*;

class LinkedListRemoveAtIndex{
 public static void main(String args[]){
  LinkedList<Integer> myList;
  myList = new LinkedList<> ();
  
  /* Add Elements to myList */
  myList.add(10);
  myList.add(20);
  myList.add(30);
  myList.add(40);
  
  System.out.println("Elements in myList are");
  System.out.println(myList);
  
  System.out.println("\nRemove Element at index 2");
  System.out.print("Element removed is ");
  System.out.println(myList.remove(2));
  
  System.out.println("\nElements in myList are");
  System.out.println(myList);
 }
}

Output
Elements in myList are
[10, 20, 30, 40]

Remove Element at index 2
Element removed is 30

Elements in myList are
[10, 20, 40]

1. Throws IndexOutOfBoundsException, if index is out of range
import java.util.*;

class LinkedListRemoveAtIndexOut{
 public static void main(String args[]){
  LinkedList<Integer> myList;
  myList = new LinkedList<> ();
  
  /* Add Elements to myList */
  myList.add(10);
  myList.add(20);
  myList.add(30);
  myList.add(40);
  
  System.out.println("Elements in myList are");
  System.out.println(myList);
  
  System.out.println("\nRemove Element at index 5");
  System.out.print("Element removed is ");
  System.out.println(myList.remove(5));
  
  System.out.println("\nElements in myList are");
  System.out.println(myList);
 }
}

Output
Elements in myList are
[10, 20, 30, 40]

Remove Element at index 5
Element removed is Exception in thread "main" java.lang.IndexOutOfBoundsExceptio
n: Index: 5, Size: 4
        at java.util.LinkedList.checkElementIndex(LinkedList.java:553)
        at java.util.LinkedList.remove(LinkedList.java:523)
        at LinkedListRemoveAtIndexOut.main(LinkedListRemoveAtIndexOut.java:19)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment