如何複製 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]

更新日期: 2019 年 10 月 11 日

327 次瀏覽

職業加速

完成課程獲得認證

開始
廣告
© . All rights reserved.