Sunday, 12 January 2020

How to get sub array or part of array


Using Arrays.copyOfRange
Arrays.copyOfRange(arr, fromIndex, toIndex) method copies the elements of array from 'fromIndex' (inclusive) to toIndex (exclusive).

int numbers[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] newArray = Arrays.copyOfRange(numbers, 4, 8);

App.java
package com.sample.app;

import java.io.IOException;
import java.util.Arrays;

public class App {

 private static void printArray(int[] arr) {
  for(int ele: arr) {
   System.out.println(ele);
  }
 }

 public static void main(String args[]) throws IOException {
  int numbers[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  
  int[] newArray = Arrays.copyOfRange(numbers, 4, 8);
  
  printArray(newArray);
 }

}


Output
5
6
7
8

Using System.arraycopy
arraycopy(Object srcArray, int srcPos, Object destArray, int destPos, int noOfElementsToCopy)

Example
int srcArray[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

int[] destArray = new int[4];

int sourceStartPosition = 4;
int destStartPosition = 0;
int noOfElementsToCopy = 4;
System.arraycopy(srcArray, sourceStartPosition, destArray, destStartPosition, noOfElementsToCopy);


App.java
package com.sample.app;

import java.io.IOException;

public class App {

 private static void printArray(int[] arr) {
  for (int ele : arr) {
   System.out.println(ele);
  }
 }

 public static void main(String args[]) throws IOException {
  int srcArray[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

  int[] destArray = new int[4];

  int sourceStartPosition = 4;
  int destStartPosition = 0;
  int noOfElementsToCopy = 4;
  System.arraycopy(srcArray, sourceStartPosition, destArray, destStartPosition, noOfElementsToCopy);

  printArray(destArray);
 }

}

Output
5
6
7
8


You may like

No comments:

Post a Comment