为什么抛出IndexOutOfBoundsException

时间:2011-04-28 10:00:01

标签: blackberry java-me

下面的代码在Field F = getField(counter)行抛出一个IndexOutOfBoundsException; 它为什么被抛出?当然,该字段存在是因为我正在基于fieldcount进行循环。或者管理员中的列表字段是否不是连续的?如果是这种情况,我应该如何从屏幕中删除类型为MyButtonField

的字段

由于

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

2 个答案:

答案 0 :(得分:5)

您尚未指定delete(f)的作用,但如果将其从字段列表中删除,则您的“有效计数”将有效降低。

要稍微重写修复问题:

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

这将来自字段的 end 而不是 start ,因此如果删除条目并且所有内容都随机播放并不重要 - 洗牌将是你已经看过的那些。

答案 1 :(得分:1)

最好的方法是使用Iterator进行迭代,然后调用方法remove()。 例如:

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

方法getFields()必须返回Field元素的集合。

相关问题