copyOf()
方法Arrays类(java.util包)的copyOf()方法接受两个参数-
一个数组(任何类型)。
表示长度的整数值。
并将给定数组的内容从起始位置复制到给定长度,然后返回新数组。
import java.util.Arrays; public class CopyingSectionOfArray { public static void main(String[] args) { String str[] = new String[10]; //填充数组 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]; //填充数组 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]