在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;
}
}
numOfSmallerArrays
的方法有误 - 应该是int numOfSmallerArrays = ((receipts.length+limit-1)/limit);
。你还需要添加一个检查if (to >= receipts.length) to = receipts.length()-1;
。 - Sergey Kalinichenkoreceipts.length
为199
,而limit
为10
,则您的表达式将产生28
而不是正确的结果20
。需要在循环结束时插入if
以避免to
的值超过限制。 - Sergey Kalinichenko