将java中的数组拆分为较小数组的最佳方法是什么?

时间:2014-11-18 17:55:11

标签: java arrays

将java方法中的数组拆分为较小的数组的最佳方法是什么?我希望能够将任何大小的数组放入takeReceipts(String[])

//Can handle any size array  
public void takeReceipts(String[] receipts){
//split array into smaller arrays, and then call handleReceipts(String[]) for every smaller array
}

//This method can only handle arrays with the size of 5 or less
private void handleReceipts(String[] receipts){
myNetworkRequest(receipts);
}

编辑:

因此将数组复制到另一个数组似乎并不高效。这样的事情会起作用吗?

    public void takeReceipts(String[] receipts){

    int limit = 5;
    int numOfSmallerArrays = (receipts.length/limit)+(receipts.length%limit);
    int from = 0;
    int to = 4;
        for (int i = 0; i < numOfSmallerArrays; i++){
            List<String> subList = Arrays.asList(receipts).subList(from, to);
            from =+ limit;
            to =+ limit;
    }

}

3 个答案:

答案 0 :(得分:4)

您可以使用Arrays.copyOfRange()

int from = 0;
int to = 4;
String[] subArray = Arrays.copyOfRange(receipts, from, to)

答案 1 :(得分:2)

如果您愿意使用List<String>代替String[]数组,则可以非常经济的方式进行分区:

List<String> subList = Arrays.asList(receipts).subList(from, to);

此方法不会复制您的数组,只提供原始收据数组的只读视图。

static final int LIMIT = 10;

public static void process(List<String> small) {
    if (small.size() > LIMIT) {
        System.out.print("Array is too big: "+small.size());
        return;
    }
    for (String s : small) {
        System.out.print(s+" ");
    }
    System.out.println();
}

public static void processBig(String[] receipts) {
    int numChunks = ((receipts.length+LIMIT-1)/LIMIT);
    int from = 0;
    int to = LIMIT;
    List<String> bigList = Arrays.asList(receipts);
    for (int i = 0 ; i != numChunks ; i++) {
        List<String> subList = bigList.subList(from, to);
        process(subList);
        from += LIMIT;
        to += LIMIT;
        if (to >= receipts.length) {
            to = receipts.length;
        }
    }
}

Demo.

采用这种方法的后果是,对原始数组元素所做的更改在视图中变得“可见”,并且您无法以任何方式更改结果subList

答案 2 :(得分:1)

public void takeReceipts(String[] receipts){
    for (int i=0; i< receipts.length; i+=5)
        handleReceipts(Arrays.copyOfRange(receipts, i, Math.min(i+4, receipts.length-1)));
}

private void handleReceipts(String[] receipts){ 
}

OR

public void takeReceipts(String[] receipts){
    for (int i=0; i< receipts.length; i+=5)
        handleReceipts(Arrays.asList(receipts).subList(i, Math.min(i+4, receipts.length-1)));
}

private void handleReceipts(List<String> receipts){
}