What is the best way to split an array in Java into smaller arrays?
•
Java
What is the best way to split an array in a Java method into smaller arrays? I want to be able to put arrays of any size into 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); }
Edit:
Therefore, copying an array to another array seems inefficient Will this happen?
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; } }
Solution
You can use arrays copyOfRange():
int from = 0; int to = 4; String[] subArray = Arrays.copyOfRange(receipts,from,to)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码