Skip to Content

Get Sub List of Java Vector Example

  1. /*
  2.   Get Sub List of Java Vector Example
  3.   This Java Example shows how to get sub list of java Vector using subList
  4.   method by providing start and end index.
  5. */
  6.  
  7. import java.util.Vector;
  8. import java.util.List;
  9.  
  10. public class GetSubListOfJavaVectorExample {
  11.  
  12.   public static void main(String[] args) {
  13.  
  14.     //create Vector object
  15.     Vector v = new Vector();
  16.    
  17.     //Add elements to Vector
  18.     v.add("1");
  19.     v.add("2");
  20.     v.add("3");
  21.     v.add("4");
  22.     v.add("5");
  23.    
  24.     /*
  25.        To get a sub list of Java Vector use
  26.        List subList(int startIndex, int endIndex) method.
  27.        This method returns an object of type List containing elements from
  28.        startIndex to endIndex - 1.
  29.     */
  30.    
  31.     List lst = v.subList(1,3);
  32.        
  33.     //display elements of sub list.
  34.     System.out.println("Sub list contains : ");
  35.     for(int i=0; i< lst.size() ; i++)
  36.       System.out.println(lst.get(i));
  37.      
  38.     /*
  39.       Sub List returned by subList method is backed by original Vector. So any
  40.       changes made to sub list will also be REFLECTED in the original Vector.
  41.     */
  42.     //remove one element from sub list
  43.     Object obj = lst.remove(0);
  44.     System.out.println(obj + " is removed from sub list");
  45.    
  46.     //print original Vector
  47.     System.out.println("After removing " + obj + " from sub list,
  48.                                             original Vector contains : ");
  49.     for(int i=0; i< v.size() ; i++)
  50.       System.out.println(v.get(i));
  51.    
  52.   }
  53.  
  54. }
  55. /*
  56. Output would be
  57. Sub list contains :
  58. 2
  59. 3
  60. 2 is removed from sub list
  61. After removing 2 from sub list, original Vector contains :
  62. 1
  63. 3
  64. 4
  65. 5
  66. */