2014-02-08 112 views
-1

我正在嘗試製作一個在屏幕上浮動的Asteroid對象的小程序。如果兩個小行星碰撞,那麼速度較慢的小行星應該分解成兩個較小的小行星。一旦小行星大小1,它應該消失。併發修改異常

當我嘗試比較兩個小行星時,我得到一個ConcurrentModificationException,我不知道爲什麼。

private volatile Collection<Asteroid> belt; 
private void handleCollisions() { 


    Collection<Asteroid> psuedoBelt = belt; 
    Iterator<Asteroid> one; 
    Iterator<Asteroid> two; 

    for (one = psuedoBelt.iterator(); one.hasNext();) { 
     Asteroid aOne = one.next(); 
     for (two = psuedoBelt.iterator(); two.hasNext();) { 

      Asteroid aTwo = two.next(); 
      if (aOne.collidesWith(aTwo)) { 
       if (aOne.getSpeed() > aTwo.getSpeed()) { 
        Collection<Asteroid> split = aTwo.split(); 
        two.remove(); 
        for (Iterator<Asteroid> three = split.iterator(); three 
          .hasNext();) { 
         psuedoBelt.add(three.next()); 
        } 
       } else { 
        Collection<Asteroid> split = aOne.split(); 
        one.remove(); 
        for (Iterator<Asteroid> three = split.iterator(); three 
          .hasNext();) { 
         psuedoBelt.add(three.next()); 
        } 
       } 
      } 
     } 
    } 

    belt = psuedoBelt; 

} 
+1

你做了什麼研究嗎?看看頁面的右側。 –

+0

http://stackoverflow.com/a/1496221/1376108 – wisemann

回答

1

首先,創建一個迭代器:

for (one = psuedoBelt.iterator(); one.hasNext();) { 

然後,第二個,在相同的集合:

for (two = psuedoBelt.iterator(); two.hasNext();) { 

然後,你與你的第二個迭代器中刪除項目:

two.remove(); 

問題是第在從集合中刪除項目時,第一個迭代器(one)不知道這種刪除。

因此,在one.next()上,它檢測到集合已被修改並引發此異常。

有2個解決方案,即:

  • 儘量只使用一個迭代器或
  • 保留項目的列表中刪除,並在迭代您的收藏後,將其刪除。
+0

如果第一個迭代器的對象具有較低的速度會怎麼樣? – Programatic

+1

@Programatic我不明白你的問題:迭代器不會同時執行,所以速度對執行順序沒有影響。 –