【问题标题】:java.lang.indexoutofboundsexception index 0 size 0java.lang.indexoutofboundsexception 索引 0 大小 0
【发布时间】:2014-02-05 06:48:43
【问题描述】:

通过复选框在数组中添加系统函数对象时,我遇到了这个 java.lang.indexoutofboundsexception 错误:

SEVERE: Servlet.service() for servlet spis threw exception
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:604)
at java.util.ArrayList.get(ArrayList.java:382)
at com.spis.dao.impl.CodesValueDaoImpl.getDescription(CodesValueDaoImpl.java:95)
at com.spis.bo.impl.CodesValueBoImpl.getDescription(CodesValueBoImpl.java:103)
at com.spis.controller.SystemUserController.viewPaged(SystemUserController.java:408)
at com.spis.controller.SystemUserController.systemUser(SystemUserController.java:48)

这是 systemFunctions:每当我将 systemFunction 添加到用户时,它都会显示错误,或者当数据库中的 systemFunction 列为空时。但是当我在数据库中设置 systemFunction=" " 时,页面显示正确,尽管显然没有 systemFunctions 数组..

String[] systemFunctions=(String[])request.getParameterValues("systemFunctions");
String appendedSysFunctions ="";

//Append system functions
if(systemFunctions!=null){
    for(int i=0;i<systemFunctions.length;i++){
        if(i==(systemFunctions.length-1)){
        appendedSysFunctions+=systemFunctions[i];
        }
        else{
        appendedSysFunctions+=systemFunctions[i] + ",";
        }
    }
}

另一个代码:

StringTokenizer st = new StringTokenizer(su.getAllowedSysFunc(), ",");
while (st.hasMoreTokens()){
    appendedSystemFunc = appendedSystemFunc + codesValueMethods.getDescription 
    (3, st.nextToken());
    if(st.hasMoreTokens()){
    appendedSystemFunc = appendedSystemFunc + ", \n";
    }
}

【问题讨论】:

  • systemFunctions 没有元素。调试你的代码。
  • 如果您以可读的方式格式化您的代码,这将非常有帮助 - 修复缩进,并在行内添加一些有用的空格。
  • 另外,您向我们展示了getDescription 一点也不明显——哪一行引发了异常? (堆栈跟踪谈到了描述——你向我们展示的所有代码都是关于“系统函数”的,我们不知道这两者之间的关系是什么。)
  • @JonSkeet 它在那里,我想,在第二个 sn-p 中。 codesValueMethods.getDescription(3, st.nextToken()); 虽然我认为这对我们没有帮助。相反,我认为问题出在ArrayList#get 所在的位置。
  • @Radiodef:嗯,这就是 to getDescription 的调用(尽管我们不知道来自什么)。但是我们需要getDescription 本身的代码。目前还不够。

标签: java indexoutofboundsexception


【解决方案1】:

你要检查systemFunctions是否为null,长度是否大于0:

if(systemFunctions!=null && systemFunctions.length>0){
  ...
}

【讨论】:

  • 不,因为for 循环会立即检查:for(int i=0;i&lt;systemFunctions.length;i++)
  • 如果数组为空,为什么还要让执行继续进行到for 循环?
  • 因为这样做比添加冗余检查更简单?无论哪种方式,这肯定不是异常的原因。
  • 已经解决了,我的错误数组是获取单个字母而不是数字的数组。它应该获取“a”而不是“1”,依此类推。愚蠢的错误。无论如何,感谢您回答我的问题.. PEace..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-11
相关资源
最近更新 更多