Home » Java programming language

Java Vector subList() Method with Example

Vector Class subList() method: Here, we are going to learn about the subList() method of Vector Class with its syntax and example.
Submitted by Preeti Jain, on March 20, 2020

Vector Class subList() method

  • subList() method is available in java.util package.
  • subList() method is used to return a set of sublist [it returns all those elements exists in a given range starting index (st_index) and ending index (en_index) and here st_index is inclusive whereas en_index is exclusive].
  • subList() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • subList() method may throw an exception at the time of returning sublist.
    • IndexOutOfBoundsException: This exception may throw when the second parameter is not in a range.
    • IllegalArgumentException: This exception may throw when the second argument is not valid.

Syntax:

    public List subList(int st_index, int en_index);

Parameter(s):

  • int st_index – represents the starting position of the returned sublist.
  • int en_index – represents the ending position of the returned sublist.

Return value:

The return type of the method is List, it returns all the element in a given range and elements are viewed in a List.

Example:

// Java program to demonstrate the example 
// of List subList(int st_index, int en_index)
// method of Vector 

import java.util.*;

public class SubListOfVector {
 public static void main(String[] args) {
  // Instantiates a Vector object  with
  // initial capacity of "10"
  Vector < String > v = new Vector < String > (10);
  List arr_l = new ArrayList();

  // By using add() method is to add the
  // elements in this v
  v.add("C");
  v.add("C++");
  v.add("JAVA");

  // By using add() method is to add the
  // elements in this arr_l
  arr_l.add("SFDC");

  // Display Vector and ArrayList
  System.out.println("v: " + v);
  System.out.println("arr_l: " + arr_l);

  // By using subList() method is to
  // return the sublist, starting at one
  // endpoint and ending at other endpoint
  arr_l = v.subList(0, 2);

  // Display updated arr_l
  System.out.println("v.subList(0,2): " + arr_l);
 }
}

Output

v: [C, C++, JAVA]
arr_l: [SFDC]
v.subList(0,2): [C, C++]



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.