How to copy a specific section of an array in Java?


Using copyOf() method

The copyOf() method of the Arrays class (java.util package) accepts two parameters −

  • an array (of any type).

  • an integer value representing length.

And copies the contents of the given array from starting position to given length and returns the new array.

Example

 Live Demo

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

Output

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

Using copyOfRange() method

The copyOfRange() method of the Arrays class (java.util package) accepts three parameters −

  • an array (of any type)

  • two integer values representing the start and end position of an array.

And copies the contents of the given array in the specified range, returns the new array.

Example

 Live Demo

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

Output

Contents of the Array:
[Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala]
Contents of the copies array:
[OpenCV, OpenNLP, JOGL, Hadoop, HBase]
raja
Published on 11-Oct-2019 10:42:31
Advertisements