如何在Java中复制数组的特定部分?
使用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]
热门推荐
10 18岁简短祝福语经典
11 除夕的拜年祝福语简短
12 好听的元旦简短祝福语
13 周年蛋糕祝福语简短英语
14 生日祝福语简短独特的
15 怀念青春祝福语简短
16 白日庆典祝福语简短英语
17 亲姐姐祝福语简短英文
18 嫂子生日的祝福语简短