我正在使用Java来迭代列表并根据特定条件对其进行更新。但由于它将使用重复列表为此提供ConcurrentModificationException
即时消息,但这仍然会提供相同的异常。使用对象和重复列表Java列表中的ConcurrentModificationException
我有一个名为Storage
的类,它表示一个虚拟存储,表示为一个文件夹(一个存储的一个文件夹),该类包含一个属性fileList
,表示它包含的文件列表(在文件夹内)。该类如下所示,
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;
}
}
我已经创建了10个存储,共使用10个对象,每个存储都有单独的文件夹。我使用for循环向所有文件夹添加了许多不同的文件,并调用this.addFile(f)
函数。
再后来我想删除满足特定标准的特定储存只有特定的文件,并添加以下删除功能的Storage
类,
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;
}
}
}
但这提供ConcurrentModificationException
在我是Enhanced For Loop
在updateFileList()
函数中使用。在增强的for循环中,我通过删除不需要的文件来更新this.getFilesList()
列表,并使用重复列表files
进行迭代。那为什么我会得到ConcurrentModificationException
异常?难道我做错了什么?