setSize(int): This method is available in java.util.Vector class of Java.
Syntax:
void java.util.Vector.setSize(int newSize)
This method takes one argument. This method sets the size of this vector.
Note:
1. If the new size is greater than the current size, new null items are added to the end of the vector.
2. If the new size is less than the current size, all components at index newSize and greater are discarded.
Parameters: One parameter is required for this method.
newSize: the new size of this vector.
Returns: NA
Throws:
ArrayIndexOutOfBoundsException - if the new size is negative
Approach 1: When no exception
Java
import java.util.Vector;public class VectorsetSize {public static void main(String[] args) {Vector<String> vector = new Vector<>();vector.add("Hello");vector.add("Java");vector.add("C++");vector.add("Program");int newSize = 5;vector.setSize(newSize);System.out.println(vector);}}
Output:
[Hello, Java, C++, Program, null]
Approach 2: ArrayIndexOutOfBoundsException
Java
import java.util.Vector;public class VectorsetSize {public static void main(String[] args) {Vector<String> vector = new Vector<>();vector.add("Hello");vector.add("Java");vector.add("C++");vector.add("Program");int newSize = -1;vector.setSize(newSize);System.out.println(vector);}}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 10 at java.base/java.util.Vector.setSize(Vector.java:284)
No comments:
Post a Comment