Friday 4 April 2014

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.

import java.util.*;

class ListSubList{
 public static void main(String args[]){
  List<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]

The returned list is backed by this list, so the changes in the returned list are reflected in this list, and vice-versa. In the above program sub list add element “1” and removes the element “35” Same affects on “myList” also.

  1. throws IndexOutOfBoundsException for an illegal endpoint index value

import java.util.*;

class ListSubListIndexOut{
 public static void main(String args[]){
  List<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(Unknown Source)
        at java.util.ArrayList.subList(Unknown Source)
        at ListSubListIndexOut.main(ListSubListIndexOut.java:12)



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment