Here in short is the situation:
for(element : array)
{
execute something that adds new elements to the array;
}
It's obvious that the newly added elements will not be processed. Is there a technique to get every elements processed?
Here is an example of this problem: I want to, given a folder, go through its depth and move all files - either under it's children or under it's children's children - to directly under the given folder. After that delete all empty folders:
Parent Folder
- Level1Folder1
- file1_1
- Level1Folder2
- Level2Folder1
- file2_1
- file2_2
- file1_2
will become:
Parent Folder
- file1_1
- file1_2
- file2_1
- file2_2
Here's that potion of my code:
public static void moveUpOneFolder(Path parent) {
try (DirectoryStream<Path> ds1 = Files.newDirectoryStream(parent)) {
for (Path p1 : ds1) {
//if this node is a dir, traverse its content
if (Files.isDirectory(p1)) {
moveUpOneFolder(p1);
}
//if this node is a file, move it up one level
else {
Path newFileName = parent.getParent().resolve(p1.getName(p1.getNameCount() - 2) + "_" + p1.getFileName());
Files.move(p1, newFileName);
}
Files.delete(p1);
}
} catch (IOException e) {
e.printStackTrace();
}
}
This recursion does not work because when execution reaches Level2Folder1, it moves file2_1 and file 2_2 up to Level1Folder2, then continue to move file1_2 to Parent Folder, ignoring file2_1 and file2_2, the newly added elements to the folder. This happens because ds1 is already initialized for the for loop, the new elements are not added to this array/stream and so are ignored.
I imagine this will not be difficult with an experienced coder, but I'm really stuck. :-)
ConcurrentModificationException.