Sunday 1 June 2014

ArrayList : subList : Get the Sub List

public List<E> subList(int fromIndex, int toIndex)
Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.

import java.util.*;

class ArrayListSubList{
 public static void main(String args[]){
  ArrayList<Integer> myList = new ArrayList<> ();
  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 ArrayListSubListIndexOut{
 public static void main(String args[]){
  ArrayList<Integer> myList = new ArrayList<> ();
  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(ArrayList.java:989)
        at java.util.ArrayList.subList(ArrayList.java:981)
        at ArrayListSubListIndexOut.main(ArrayListSubListIndexOut.java:12)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment