如何複製 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]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP