'My code returns an error when trying to split a vector
I have a problem with a Java code and I can't solve it, I have a Vector with 3.529 .txt files and I wanted to split it into 6 other vectors. I'm using the code below to split the vector. What am I doing wrong?
int cut = filesToProcess.size() / 6;
List<List<File>> arrays = new ArrayList<>();
for (int i = 0; i < filesToProcess.size(); i = i + cut) {
arrays.add(filesToProcess.subList(i, i + cut)); //line 35
}
Solution 1:[1]
arrays.add(filesToProcess.subList(i, i + cut));
In you for statement, i < fileToProcess.size(), so if i == fileToProcess.size() - 1, i + cut is definitely out of range.
The idea to solve this problem is to change the for statement to:
i < filesToProcess.size() - cut.
Edit: as passer-by said, divide int may have decimal loss so you can’t cut perfectly.
Solution 2:[2]
There are two issues with your approach:
- 3529 / 6 is not even so you'll end up with 7 vectors instead of 6. So you need to round up your
cutwithint cut = (int) Math.ceil((double) filesToProcess.size() / 6); - When you have uneven division, your last vector won't have the same number of items as the others so you will always get
IndexOutOfBounds. This is clearly stated in your exception: "toIndex: 4116" where.subList()is trying to get items up to index 4116. To fix this, you need to check the "to' part of.subList()to make sure it's not too large.
int cut = (int) Math.ceil((double)items.size() / 6);
List<List<File>> arrays = new ArrayList<>();
for (int i = 0; i < filesToProcess.size(); i = i + cut) {
arrays.add(filesToProcess.subList(i, Math.min(i + cut, filesToProcess.size())));
}
With this, you should get the following split:
Vector = 1 => size = 589
Vector = 2 => size = 589
Vector = 3 => size = 589
Vector = 4 => size = 589
Vector = 5 => size = 589
Vector = 6 => size = 584
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | engine |
| Solution 2 |

