简体   繁体   English

找出某个数组范围内的值/元素

[英]find out values / elements of a certain range of an array

I would like to find out if there is a java function that can check the values from index 0-5?我想知道是否有一个java函数可以检查索引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 } .不使用循环是否有一个函数将子 Array1 [0-5] 中的元素标识为 { 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.谢谢你的帮助。

You can use Arrays.copyOfRange(arr, start, end) this will return you an array containing the specified range from the original arr array.您可以使用Arrays.copyOfRange(arr, start, end)这将返回一个包含原始arr数组中指定范围的数组。

start is inclusive, end is exclusive start是包容的, end是排斥的

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

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). sublist是原始列表的受限视图(它是具有修改的开始和结束索引的相同列表)。

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

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:但最终他们使用System.arraycopy(...)所以你可以直接使用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM