java.util.Vector.copyInto() Method

Advertisements


Description

The copyInto(Object[] anArray) method is used to copy the components of this vector into the specified array. The item at index k in this vector is copied into component k of the array.It means the position of elements are same in both the vector and array. The array must be big enough to hold all the objects in this vector otherwise an IndexOutOfBoundsException is thrown.

Declaration

Following is the declaration for java.util.Vector.copyInto() method

public void copyInto(Object[] anArray)

Parameters

  • anArray--This is the array into which the components get copied.

Return Value

Return type is void so does not return anything.

Exception

  • NullPointerException--if the given array is null.

Example

The following example shows the usage of java.util.Vector.copyInto() method.

package com.tutorialspoint;

import java.util.Vector;

public class VectorDemo {
   public static void main(String[] args) {
      // create an empty Vector vec with an initial capacity of 4      
      Vector<Integer> vec = new Vector<Integer>(4);
      
      Integer anArray[]=new Integer[4];
      
      anArray[0] = 100;
      anArray[1] = 100;
      anArray[2] = 100;
      anArray[3] = 100;

      // use add() method to add elements in the vector
      vec.add(4);
      vec.add(3);
      vec.add(2);
      vec.add(1);
      
      // numbers in the array before copy
      System.out.println("Numbers in the array before copy");
      for (Integer number : anArray) {         
         System.out.println("Number = " + number);
      }
      
      // copy into the array
      vec.copyInto(anArray);
      
      // numbers in the array after copy
      System.out.println("Numbers in the array after copy");
      for (Integer number : anArray) {         
         System.out.println("Number = " + number);
      }                
   }
}

Let us compile and run the above program, this will produce the following result.

Numbers in the array before copy
Number = 100
Number = 100
Number = 100
Number = 100
Numbers in the array after copy
Number = 4
Number = 3
Number = 2
Number = 1



Advertisements
Advertisements