2016-10-01 39 views
0

我正在使用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 LoopupdateFileList()函數中使用。在增強的for循環中,我通過刪除不需要的文件來更新this.getFilesList()列表,並使用重複列表files進行迭代。那爲什麼我會得到ConcurrentModificationException異常?難道我做錯了什麼?

回答

1

不能從列表中有remove()刪除元素,而迭代。但是你可以通過使用迭代器來實現:

public void updateFileList() { 
     List<File> files = this.getFilesList(); 
     Iterator<File> iter = files.iterator(); 
     while (iter.hasNext()) { 
      File f = iter.next(); 
      if (/*Deletion criteria satisfied*/) 
      { 
       f.delete(); 
       iter.remove(); 
       this.occupiedSize = this.occupiedSize - f.length()/1048576.0; 
      } 
     } 
    } 
0

您在遍歷列表時從列表中移除元素。

嘗試從

public List<File> getFilesList() // Get list of files in storage 
{ 
    return this.filesList; 
} 

改變getFilesList()方法

public List<File> getFilesList() // Get list of files in storage 
{ 
    return new ArrayList<File>(this.filesList); 
} 
1

你也可以使用ListIterator而不是每個都使用ListIterator。並使用方法iterator.remove從列表中刪除文件。

public void updateFileList() 
{ 
    List<File> files = new ArrayList<File>(); 
    files = this.getFilesList(); 
    Iterator<File> it = files.iterator(); 
     while (it.hasNext()) { 

      if (deletion condition) { 

       it.remove(); 

      } 
     } 
} 

也看到在java中鏈接關於快速失敗和故障安全的迭代器是這裏fail-fast and fail-safe iterator in java