2016-10-01 41 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