Vector copyInto(Object[]) in Java

copyInto(Object[]): This method is available in java.util.Vector class of Java.

Syntax:

void java.util.Vector.copyInto(Object[] anArray)

This method takes one argument. This method copies the components of this vector into the specified array. The item at index k in this vector is copied into component k of anArray.

Parameters: One parameter is required for this method.

anArray: the array into which the components get copied.

Throws:

1. NullPointerException - if the given array is null.

2. IndexOutOfBoundsException - if the specified array is not large enough to hold all the components of this vector.

3. ArrayStoreException - if a component of this vector is not of a runtime type that can be stored in the specified array.

Approach 1: When no exception

Java

import java.util.Arrays;
import java.util.Vector;

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

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

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

        Object anArray[] = new Object[vector.size()];
        vector.copyInto(anArray);
        System.out.println(Arrays.toString(anArray));
    }
}

Output:

[Hello, Java, C++, Program]


Approach 2: NullPointerException 

Java

import java.util.Arrays;
import java.util.Vector;

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

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

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

        Object anArray[] = null;
        vector.copyInto(anArray);
        System.out.println(Arrays.toString(anArray));
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.lang.System.arraycopy(Native Method) at java.base/java.util.Vector.copyInto(Vector.java:205)



Approach 3: IndexOutOfBoundsException 

Java

import java.util.Arrays;
import java.util.Vector;

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

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

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

        Object anArray[] = new Object[vector.size() - 1];
        vector.copyInto(anArray);
        System.out.println(Arrays.toString(anArray));
    }
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: arraycopy: last destination index 4 out of bounds for object array[3] at java.base/java.lang.System.arraycopy(Native Method) at java.base/java.util.Vector.copyInto(Vector.java:205)


No comments:

Post a Comment