我在Java中有一个整数数组,我只想使用它的一部分。我知道在Python中,你可以这样做数组[index:],它从索引中返回数组。这在Java中是可能的吗?


当前回答

查看copyOfRange;例子:

int[] arr2 = Arrays.copyOfRange(arr,0,3);

其他回答

您可以将数组包装为列表,并请求它的子列表。

MyClass[] array = ...;
List<MyClass> subArray = Arrays.asList(array).subList(index, array.length);

如果您使用的是Java 1.6或更高版本,则可以使用数组。copyOfRange复制数组的一部分。来自javadoc:

Copies the specified range of the specified array into a new array. The initial index of the range (from) must lie between zero and original.length, inclusive. The value at original[from] is placed into the initial element of the copy (unless from == original.length or from == to). Values from subsequent elements in the original array are placed into subsequent elements in the copy. The final index of the range (to), which must be greater than or equal to from, may be greater than original.length, in which case false is placed in all elements of the copy whose index is greater than or equal to original.length - from. The length of the returned array will be to - from.

这里有一个简单的例子:

/**
 * @Program that Copies the specified range of the specified array into a new 
 * array.
 * CopyofRange8Array.java 
 * Author:-RoseIndia Team
 * Date:-15-May-2008
 */
import java.util.*;
public class CopyofRange8Array {
    public static void main(String[] args) {
       //creating a short array
       Object T[]={"Rose","India","Net","Limited","Rohini"};
        // //Copies the specified  short array upto specified range,
        Object T1[] = Arrays.copyOfRange(T, 1,5);
        for (int i = 0; i < T1.length; i++) 
            //Displaying the Copied short array upto specified range
            System.out.println(T1[i]);
    }

}

你可以试试:

System.arraycopy(sourceArray, 0, targetArray, 0, targetArray.length);// copies whole array

// copies elements 1 and 2 from sourceArray to targetArray
System.arraycopy(sourceArray, 1, targetArray, 0, 2); 

系统请参见javadoc。

你可以在整数arr上使用subList(int fromIndex, int toIndex)方法,就像这样:

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(2);
        arr.add(3);
        arr.add(4);
        List<Integer> partialArr = arr.subList(1, 3);

        // print the subArr
        for (Integer i: partialArr)
            System.out.println(i + " ");
    }
}

输出将是:2 3。

注意,subList(int fromIndex, int toIndex)方法对它接收到的第二个变量(var2 - 1)执行- 1,我不知道确切的原因,但这就是发生的事情,可能是为了减少超出数组大小的机会。

查看copyOfRange;例子:

int[] arr2 = Arrays.copyOfRange(arr,0,3);