IndexOutofBounds此给定方案中的异常解析

时间:2012-01-30 04:47:40

标签: java java-ee

需要弄清楚摆脱java.lang.IndexOutofBoundsException: Index: 1, Size: 0

的以下问题的最佳方法

如代码所示,此异常在条件

的任何时候发生
if(tempBean.getCustomerState.equalsIgnoreCase("MD")    

为false,外部for循环继续执行。这使代码看起来像:

finalBeanOne.add(1, tempBeanOne.get(1));

但是由于finalBeanOne列表从未在索引0处具有元素(因为if条件在第一次迭代时为false),因此抛出IndexOutofBoundsException。修复此方案的最佳方法是什么?

ArrayList<BeanOne> finalBeanOne = new ArrayList<BeanOne>();

ArrayList<BeanOne> tempBeanOne = (cast) DAO.getBeanOneList();

   for(int i=0; i< tempBeanOne.size; i++ ) {

      if(tempBeanOne.getCustomerState.equalsIgnoreCase("MD") {

        finalBeanOne.add(i, tempBeanOne.get(i));
      }


  }

3 个答案:

答案 0 :(得分:4)

您应该使用equals()方法来比较String个对象

您只需使用add(Object),或者如果您需要索引作为密钥,请转到Map<integer, Object>

答案 1 :(得分:1)

无论您检查相等性的方式如何,您都会在“unitialized index”中添加新数组列表。请记住,对于标准数组列表,在特定索引处添加类似于在该索引处设置,因为需要在该索引处实际 存在 的元素:

public void add(int index,
                E element)
Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

Throws:
IndexOutOfBoundsException - if the index is out of range (index > 0 || index < size())

要解决您的问题,只需在“结果”列表中调用add

finalBeanOne.add(tempBeanOne.get(i));

当然,您还可以通过使用增强型逻辑来提高代码效率:

List<BeanOne> finalBeanOne = new ArrayList<BeanOne>();
List<BeanOne> tempBeanOne = (List<BeanOne>) DAO.getBeanOneList();

for(BeanOne tempBean: tempBeanOne) {
    if(tempBean.getCustomerState().equalsIgnoreCase("MD") {
        finalBeanOne.add(tempBean);
    }
}

答案 2 :(得分:0)

在开始for循环之前,检查tempBeanOne变量的大小。更改您的比较代码如下。

  if(tempBean(i).getCustomerState.equals ("MD") )
  {

    finalBeanOne.add(i, tempBeanOne.get(i));
  }