我正在使用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
異常?難道我做錯了什麼?