Java教程

Java Vector copyInto()

Java Vector类的 copyInto()方法用于将正在使用的Vector 元素复制到指定的数组。在这种情况下,向量和数组中元素的位置都相同。

语法:

下面是 copyInto( )方法:
public void copyInto(Object[] anArray)

参数:

参数 说明 必需/可选
anArray 这是将组件复制到的数组。 必需

返回:

copyInto()方法的返回类型为 void ,因此它不会返回

异常:

NullPointerException -如果指定的数组为null,则此方法引发了异常。
IndexOutOfBoundsException -如果指定的数组无法容纳此向量的所有组件,则此方法引发异常。

兼容性版本:

Java 1.2及更高版本

示例1:

import java.util.Vector;
public class VectorCopyIntoExample1 {  
    public static void main(String arg[]) {       
        //Create an empty Vector1
        Vector<Integer> vec = new Vector<>(5);  
        //Add elements in the vector
        vec.add(1);
        vec.add(2);
        vec.add(3);
        vec.add(4);
        vec.add(5);                   
        Integer[] arr = new Integer[5];        
        //copy elements of vector into an array
        vec.copyInto(arr);  
        System.out.println("Elements in an array are: ");
        for(Integer num : arr)
        {
            System.out.println(num);
        }      
     }            
}
输出:
Elements in an array are: 
1
2
3
4
5

示例2:

import java.util.Vector;
public class VectorCopyIntoExample2 {  
    public static void main(String arg[]) {       
        //Create an empty Vector
            Vector<String> vector1 = new Vector<>();        
            //Add elements to the Vector
            vector1.add("Rahul");
            vector1.add("Vijay");
            vector1.add("Shyam");
            vector1.add("Rohan");        
            //Create an new Array with intial size 4
            String tempArray[] = new String[4];       
            //Copy Vector element to Array
            vector1.copyInto(tempArray);       
            System.out.println("Elements of the Array: ");
            //Print elements of an Array
            for(String temp : tempArray)
            {
                System.out.println(temp);
            }
    }            
}
输出:
Elements of the Array: 
Rahul
Vijay
Shyam
Rohan

示例3:

import java.util.*;
public class VectorCopyIntoExample3 {  
    public static void main(String arg[]) {       
         Vector<Integer> vec = new Vector<Integer>();
         vec.add(4);
         vec.add(3);
         vec.add(2);
         vec.add(1);        
         Integer anArray[] = new Integer[3];               
         //copy vector elements into an array
         vec.copyInto(anArray);         
         for (Integer number : anArray) {         
             System.out.println("Number= " + number);
         }                
    }            
}
输出:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
    at java.base/java.lang.System.arraycopy(native Method)
    at java.base/java.util.Vector.copyInto(Vector.java:200)
    at myPackage.VectorCopyIntoExample3.main(VectorCopyIntoExample3.java:12)

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4