2011-04-28 90 views
0

下面的代碼在行上引發IndexOutOfBoundsException Field f = getField(counter); 它爲什麼被拋出?當然,這個字段的存在是因爲我是基於fieldcount循環的。或者,經理中的列表字段沒有被保證是順序的?如果這是我應該怎麼刪除一個屏幕,是類型的字段的情況下 - MyButtonField爲什麼拋出IndexOutOfBoundsException

感謝

 int fieldCount = getFieldCount() - 1; 
     if(fieldCount > 1){ 
      for(int counter = 0; counter <= fieldCount ; ++counter){ 
       Field f = getField(counter); 
       if(f instanceof MyButtonField){     
        delete(f); 
       } 
      } 
     } 
+0

你試過調試它看看你傳遞給getField()的值是什麼? – Augusto 2011-04-28 10:02:05

回答

5

您還沒有指定什麼delete(f)做,但如果從字段列表中刪除,那麼你的「有效計數」將會有效減少。

要重寫這個有點解決問題:

for (int index = getFieldCount() - 1; index >= 0; index--){ 
    Field f = getField(index); 
    if (f instanceof MyButtonField) { 
     delete(f); 
    } 
} 

這會從年底的領域,而不是開始,所以如果你刪除它並不重要入場和一切洗牌 - 洗牌的項目將是你已經看過的項目。

+0

295K !!!!!!!!!!你怎麼有這麼多的名聲?.............:-O ......太多了。 – 2011-04-28 10:07:39

+0

謝謝你回答如此之快,是的工作。 – 2011-04-28 10:08:48

1

最好的方法是使用Iterator進行迭代,然後調用方法remove()。 實施例:

 for(Iterator it = getFields().iterator();it.hasNext()){ 
      Field f = (Field) it.next(); 
      if(f instanceof MyButtonField){     
       it.remove(); 
      } 
     } 

方法getFields()必須返回領域元素的集合。

+1

原始問題沒有指定它,但BlackBerry使用java-me,它沒有迭代器 - 它具有枚舉和枚舉不支持'remove()' – 2011-04-28 17:47:05

相關問題