I am using Java to iterate a list and update it based on certain criteria. But since it will provide ConcurrentModificationException
im using a duplicate list for this but this still provides the same exception.
I have a class named Storage
that denotes a virtual storage that is represented as a folder (one folder for one storage) and this class contains an attribute fileList
that denotes the list of files it contains (within the folder). The class is as given below,
public class Storage
{
// List of files in storage
private List<File> fileList = new ArrayList<File>();
// Occupied size in MB
private double occupiedStorage;
// Location of storage folder
private String location;
public Storage(String loca) // Create a storage
{
this.location = loca;
this.occupiedSize = 0;
}
public addFile(File f) // Add file to storage
{
// Copy the file to folder in location 'this.location'
this.fileList.add(f);
this.occupiedSize = this.occupiedSize + f.length()/1048576.0;
}
public List<File> getFilesList() // Get list of files in storage
{
return this.filesList;
}
public double getOccupiedSize() // Get the occupied size of storage
{
return this.occupiedSize;
}
}
I have created a total of 10 storage using 10 objects and each of them has separate folders. The i added many different files to all the folders using for loop and calling the this.addFile(f)
function.
Then later i want to delete only specific files from specific storages that satisfy a certain criteria and i added the following deletion function to the Storage
class,
public void updateFileList()
{
List<File> files = new ArrayList<File>();
files = this.getFilesList();
for (File f : files)
{
if (/*Deletion criteria satisfied*/)
{
f.delete();
this.getFilesList().remove(f);
this.occupiedSize = this.occupiedSize - f.length()/1048576.0;
}
}
}
But this provides ConcurrentModificationException
in the Enhanced For Loop
that i am using in the updateFileList()
function. Within the enhanced for loop i am updating the this.getFilesList()
list by removing the unwanted file, and the iteration is made using a duplicate list files
. Then why am i getting the ConcurrentModificationException
exception?? Am i doing something wrong?