Vector subList(int, int) in Java

subList(int, int): This method is available in java.util.Vector class of Java.

Syntax:

List<K> java.util.Vector.subList(int fromIndex, int toIndex)

This method takes two arguments. This method returns a view of the portion of this List between fromIndex, inclusive, and toIndex, exclusive.

Note: The returned List is backed by thisList, so changes in the returned List are reflected in this list, and vice-versa.

Parameters: Two parameters are required for this method.

fromIndex: low endpoint (inclusive) of the subList.

toIndex: high endpoint (exclusive) of the subList.

Returns: a view of the specified range within this List.

Throws:

1. IndexOutOfBoundsException - if an endpoint index value is out of range (fromIndex < 0 || toIndex > size).

2. IllegalArgumentException - if the endpoint indices are out of order (fromIndex > toIndex)

Approach 1: When no exception

Java

import java.util.Vector;

public class VectorsubList {
    public static void main(String[] args) {

        Vector<String> vector = new Vector<>();

        vector.add("Hello");
        vector.add("Java");
        vector.add("C++");
        vector.add("Program");

        int fromIndex = 0, toIndex = 2;

        System.out.println(vector.subList(fromIndex,
toIndex));
    }
}

Output:

[Hello, Java]


Approach 2: IndexOutOfBoundsException 

Java

import java.util.Vector;

public class VectorsubList {
    public static void main(String[] args) {

        Vector<String> vector = new Vector<>();

        vector.add("Hello");
        vector.add("Java");
        vector.add("C++");
        vector.add("Program");

        int fromIndex = 0, toIndex = 5;

        System.out.println(vector.subList(fromIndex,
toIndex));
    }
}

Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: toIndex = 5 at java.base/java.util.AbstractList.subListRangeCheck(AbstractList.java:507) at java.base/java.util.AbstractList.subList(AbstractList.java:497) at java.base/java.util.Vector.subList(Vector.java:1121)



Approach 3: IllegalArgumentException

Java

import java.util.Vector;

public class VectorsubList {
    public static void main(String[] args) {

        Vector<String> vector = new Vector<>();

        vector.add("Hello");
        vector.add("Java");
        vector.add("C++");
        vector.add("Program");

        int fromIndex = 5, toIndex = 2;

        System.out.println(vector.subList(fromIndex, toIndex));
    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: fromIndex(5) > toIndex(2) at java.base/java.util.AbstractList.subListRangeCheck(AbstractList.java:509) at java.base/java.util.AbstractList.subList(AbstractList.java:497) at java.base/java.util.Vector.subList(Vector.java:1121)


No comments:

Post a Comment