gpt4 book ai didi

java - 将 Java 中的数组拆分为更小数组的最佳方法?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:25:35 27 4
gpt4 key购买 nike

将 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;
}

}

最佳答案

您可以使用 Arrays.copyOfRange() :

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

关于java - 将 Java 中的数组拆分为更小数组的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27000788/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com