Home > Software engineering >  find out values / elements of a certain range of an array
find out values / elements of a certain range of an array

Time:07-07

I would like to find out if there is a java function that can check the values from index 0-5? For example. Without using a loop Is there a function that identifies the elements in sub Array1 [0-5] as { 1,2,3,4,5} int Array1[]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 }. Thanks for your help.

CodePudding user response:

You can use Arrays.copyOfRange(arr, start, end) this will return you an array containing the specified range from the original arr array.

start is inclusive, end is exclusive

e.g. for your case

int[] arr = new int[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
int[] subArr = Arrays.copyOfRange(arr, 0, 5);

CodePudding user response:

I would not use arrays. Lists are easier to use. Especially if you want to work with sub arrays since there is no copying using lists. The sublist is a constrained view of the original list (it's the same list with modified start and ending indices).

List<Integer> intList = List.of(1,2,3,4,5,6,7);
List<Integer> intSublist = list.subList(0,5);

System.out.println(intSublist.equals(List.of(1,2,3,4,5)));

prints

true

CodePudding user response:

There are more then one way to do this but this could be one of it:

int[] arr = new int[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};

//starts everytime by element 0
int[] subArr = Arrays.copyOf(arr, 5);

or this

int[] arr = new int[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
int[] subArr = Arrays.copyOfRange(arr, 0,5);

but end the end they use System.arraycopy(...) so you can use this directly:

int[] arr = new int[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
int[] subArr = new int[5];

//starts at the specified index here 0
System.arraycopy(arr, 0, subArr, 0, subArr.length);
  •  Tags:  
  • java
  • Related