在 Java 中只获取数组的一部分? [英] Get only part of an Array in Java?
问题描述
我在 Java 中有一个整数数组,我只想使用其中的一部分.我知道在 Python 中你可以做这样的事情 array[index:] 并且它从索引返回数组.在 Java 中是否有这种可能.
Java 中数组的长度是不可变的.因此,您需要将所需部分复制到新数组中.
使用 java 中的 copyOfRange
方法.util.Arrays 类:
int[] newArray = Arrays.copyOfRange(oldArray, startIndex, endIndex);
<块引用>
startIndex 是要复制的范围的初始索引,包括.
endIndex 是要复制的范围的最终索引,独占.(这个索引可能位于数组之外)
例如:
//索引 0 1 2 3 4int[] arr = {10, 20, 30, 40, 50};Arrays.copyOfRange(arr, 0, 2);//返回 {10, 20}Arrays.copyOfRange(arr, 1, 4);//返回 {20, 30, 40}Arrays.copyOfRange(arr, 2, arr.length);//返回 {30, 40, 50}(长度 = 5)
I have an array of Integers in Java, I would like use only a part of it. I know in Python you can do something like this array[index:] and it returns the array from the index. Is something like this possible in Java.
The length of an array in Java is immutable. So, you need to copy the desired part into a new array.
Use copyOfRange
method from java.util.Arrays class:
int[] newArray = Arrays.copyOfRange(oldArray, startIndex, endIndex);
startIndex is the initial index of the range to be copied, inclusive.
endIndex is the final index of the range to be copied, exclusive. (This index may lie outside the array)
E.g.:
//index 0 1 2 3 4
int[] arr = {10, 20, 30, 40, 50};
Arrays.copyOfRange(arr, 0, 2); // returns {10, 20}
Arrays.copyOfRange(arr, 1, 4); // returns {20, 30, 40}
Arrays.copyOfRange(arr, 2, arr.length); // returns {30, 40, 50} (length = 5)
这篇关于在 Java 中只获取数组的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!