如何在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]
热门推荐
1 训练狗狗工作
4 狗狗定点排便训练
5 狗狗训练吠叫
6 狗狗尿垫训练
7 狗狗训练座
8 狗狗训练攻略
9 狗狗训练记
10 做训练狗狗
11 狗狗训练词
12 狗狗谢谢怎么训练
13 狗狗训练如厕
14 狗狗太凶怎么训练
15 狗狗训练它
16 狗狗克制训练
17 训练基地狗狗
18 怎么样训练狗狗大小硬