如何复制 Java 数组中的特定部分?
使用 copyOf() 方法
Arrays 类(java.util 包)的 copyOf() 方法接受两个参数:
一个数组(任何类型)。
一个表示长度的整型值。
它复制给定数组内容从开始位置到指定长度,并返回新数组。
示例
import java.util.Arrays; public class CopyingSectionOfArray { public static void main(String[] args) { String str[] = new String[10]; //Populating the array str[0] = "Java"; str[1] = "WebGL"; str[2] = "OpenCV"; str[3] = "OpenNLP"; str[4] = "JOGL"; str[5] = "Hadoop"; str[6] = "HBase"; str[7] = "Flume"; str[8] = "Mahout"; str[9] = "Impala"; System.out.println("Contents of the Array: \n"+Arrays.toString(str)); String[] newArray = Arrays.copyOf(str, 5); System.out.println("Contents of the copies array: \n"+Arrays.toString(newArray)); } }
输出
Contents of the Array: [Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala] Contents of the copies array: [Java, WebGL, OpenCV, OpenNLP, JOGL]
使用 copyOfRange() 方法
Arrays 类(java.util 包)的 copyOfRange() 方法接受三个参数:
一个数组(任何类型)
两个表示数组开始位置和结束位置的整型值。
它复制给定数组在指定范围内的内容,并返回新数组。
示例
import java.util.Arrays; public class CopyingSectionOfArray { public static void main(String[] args) { String str[] = new String[10]; //Populating the array str[0] = "Java"; str[1] = "WebGL"; str[2] = "OpenCV"; str[3] = "OpenNLP"; str[4] = "JOGL"; str[5] = "Hadoop"; str[6] = "HBase"; str[7] = "Flume"; str[8] = "Mahout"; str[9] = "Impala"; System.out.println("Contents of the Array: \n"+Arrays.toString(str)); String[] newArray = Arrays.copyOfRange(str, 2, 7); System.out.println("Contents of the copies array: \n"+Arrays.toString(newArray)); } }
输出
Contents of the Array: [Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala] Contents of the copies array: [OpenCV, OpenNLP, JOGL, Hadoop, HBase]
广告