Tuesday, 27 May 2014

LinkedList : subList : Get the Sub List

List<E> subList(int fromIndex, int toIndex)
Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. Methods equals, hashCode, listIterator, removeRange, subList are inherited from AbstractList.

import java.util.*;

class LinkedListSubList{
 public static void main(String args[]){
  LinkedList<Integer> myList = new LinkedList<> ();
  List<Integer> sub;
   
  /* Add Elements to myList */
  for(int i=0; i < 90; i+=5)
   myList.add(i);
   
  sub = myList.subList(5, 15);
  
  System.out.println("Elements in myList are");
  System.out.println(myList);
  System.out.println("Elements in sub List are");
  System.out.println(sub);
  
  System.out.println("\nAdd 1 to sub List");
  sub.add(1);
  
  System.out.println("Elements in myList are");
  System.out.println(myList);
  System.out.println("Elements in sub List are");
  System.out.println(sub);
  
  System.out.println("\nRemove 35 from the sub List");
  sub.remove(2);
  
  System.out.println("Elements in myList are");
  System.out.println(myList);
  System.out.println("Elements in sub List are");
  System.out.println(sub);
 } 
}

Output
Elements in myList are
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85]
Elements in sub List are
[25, 30, 35, 40, 45, 50, 55, 60, 65, 70]

Add 1 to sub List
Elements in myList are
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 1, 75, 80, 85]
Elements in sub List are
[25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 1]

Remove 35 from the sub List
Elements in myList are
[0, 5, 10, 15, 20, 25, 30, 40, 45, 50, 55, 60, 65, 70, 1, 75, 80, 85]
Elements in sub List are
[25, 30, 40, 45, 50, 55, 60, 65, 70, 1]

1. Throws IndexOutOfBoundsException for an illegal endpoint index value
import java.util.*;

class LinkedListSubListIndexOut{
 public static void main(String args[]){
  LinkedList<Integer> myList = new LinkedList<> ();
  List<Integer> sub;
   
  /* Add Elements to myList */
  myList.add(10);
  myList.add(20);
  
  sub = myList.subList(0, 5);
 } 
}

Output
Exception in thread "main" java.lang.IndexOutOfBoundsException: toIndex = 5
        at java.util.ArrayList.subListRangeCheck(Unknown Source)
        at java.util.ArrayList.subList(Unknown Source)
        at ListSubListIndexOut.main(ListSubListIndexOut.java:12)

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment