Computer >> Máy Tính >  >> Lập trình >> Java

Làm cách nào để sao chép một phần cụ thể của một mảng trong Java?

Sử dụng phương thức copyOf ()

copyOf () phương thức của lớp Mảng (gói java.util) chấp nhận hai tham số -

  • một mảng (thuộc bất kỳ loại nào).

  • một giá trị số nguyên đại diện cho độ dài.

Và sao chép nội dung của mảng đã cho từ vị trí bắt đầu đến độ dài đã cho và trả về mảng mới.

Ví dụ

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));
   }
}

Đầu ra

Contents of the Array:
[Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala]
Contents of the copies array:
[Java, WebGL, OpenCV, OpenNLP, JOGL]

Sử dụng phương thức copyOfRange ()

copyOfRange () phương thức của lớp Mảng (gói java.util) chấp nhận ba tham số -

  • một mảng (thuộc bất kỳ loại nào)

  • hai giá trị số nguyên đại diện cho vị trí bắt đầu và kết thúc của một mảng.

Và sao chép nội dung của mảng đã cho trong phạm vi được chỉ định, trả về mảng mới.

Ví dụ

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));
   }
}

Đầu ra

Contents of the Array:
[Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala]
Contents of the copies array:
[OpenCV, OpenNLP, JOGL, Hadoop, HBase]