Java Vector copyInto()方法

Java Vector copyInto()方法

java.util.vector.copyInto()方法用于将该向量的所有元素复制到另一个数组中,该数组有足够的空间来容纳该向量的所有组件。需要注意的是,元素的索引保持不变。数组中的元素会被向量中的元素所取代。

语法

Vector.copyInto(Object array[])

参数: 参数array[]是矢量的类型。这是一个数组,向量中的元素将被复制到这个数组中。

返回值: 该方法为无效类型,不返回任何值。

异常: 如果数组是空的,该方法会抛出NullPointerException。

下面的程序说明了Java.util.Vector.copyInto()方法。

程序1 :

// Java code to illustrate copyInto()
import java.util.*;
  
public class VectorDemo {
    public static void main(String args[])
    {
        // Creating an empty Vector
        Vector<String> vec_tor = new Vector<String>();
  
        // Use add() method to add elements into the Vector
        vec_tor.add("Welcome");
        vec_tor.add("To");
        vec_tor.add("Geeks");
        vec_tor.add("4");
        vec_tor.add("Geeks");
  
        // Displaying the Vector
        System.out.println("Vector: " + vec_tor);
  
        // Creating an array
        String arr[] = new String[6];
  
        arr[0] = "Hello";
        arr[1] = "World";
  
        // Displaying the initial array
        System.out.println("The initial array is: ");
        for (String str : arr)
            System.out.println(str);
  
        // Copying
        vec_tor.copyInto(arr);
  
        // The final array
        System.out.println("The final array is: ");
        for (String str : arr)
            System.out.println(str);
    }
}

输出:

Vector: [Welcome, To, Geeks, 4, Geeks]
The initial array is: 
Hello
World
null
null
null
null
The final array is: 
Welcome
To
Geeks
4
Geeks
null

程序2

// Java code to illustrate copyInto()
import java.util.*;
  
public class VectorDemo {
    public static void main(String args[])
    {
        // Creating an empty Vector
        Vector<Integer> vec_tor = new Vector<Integer>();
  
        // Use add() method to add elements into the Vector
        vec_tor.add(10);
        vec_tor.add(20);
        vec_tor.add(30);
        vec_tor.add(40);
        vec_tor.add(50);
  
        // Displaying the Vector
        System.out.println("Vector: " + vec_tor);
  
        // Creating an array
        Integer arr[] = new Integer[6];
  
        arr[0] = 50;
        arr[1] = 60;
        arr[2] = 70;
        arr[3] = 80;
        arr[4] = 90;
  
        // Displaying the initial array
        System.out.println("The initial array is: ");
        for (Integer str : arr)
            System.out.println(str);
  
        // Copying
        vec_tor.copyInto(arr);
  
        // The final array
        System.out.println("The final array is: ");
        for (Integer str : arr)
            System.out.println(str);
    }
}

输出:

Vector: [10, 20, 30, 40, 50]
The initial array is: 
50
60
70
80
90
null
The final array is: 
10
20
30
40
50
null

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程