IndexOutOFBound异常,索引0大小为0,链接列表为

时间:2015-08-21 18:33:12

标签: java intellij-idea

 java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.LinkedList.checkElementIndex(LinkedList.java:553)
    at java.util.LinkedList.get(LinkedList.java:474)
    at com.comcast.guide.actionhandlers.MiniGuideActions.checkChannelFocus(MiniGuideActions.java:79)
    at com.comcast.guide.functests.MiniGuideTest.checkChannelFocus(MiniGuideTest.java:34)`

我看到这行

中有错误
String currentAiringChannelNumber=moduleModel.getGenerators().get(0).getStringParam(TP_CHANNEL_NUMBER)== null ? "" : moduleModel.getGenerators().get(0).getStringParam(TP_CHANNEL_NUMBER);

E get方法:

public E get(int index) {
       checkElementIndex(index);
         return node(index).item;
}

checkElementIndex方法:

private String outOfBoundsMsg(int index) {
     return "Index: "+index+", Size: "+size;
}
private void checkElementIndex(int index) {
    if (!isElementIndex(index))
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private void checkPositionIndex(int index) {
    if (!isPositionIndex(index))
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

我是Java新手,我无法确定应该在何处更改代码。虽然测试用例正在执行  在流程中,它最终返回了这个例外而且它正在给予  最后的异常消息。有人可以帮我解决吗?

5 个答案:

答案 0 :(得分:0)

这意味着您尝试访问index 0处的对象(所以第一个对象),尽管LinkedList中没有对象(其size为0)。因此,您需要在尝试访问之前添加对象。

在尝试访问其中的对象之前,您可以检查LinkedList中是否有list.size() > 0的任何对象。

答案 1 :(得分:0)

您需要检查LinkedList并确保其已填充。下面是一个例子,我分成了多个if语句,使其更具可读性。

String currentAiringChannelNumber = "";
if (moduleModel.getGenerators() != null && moduleModel.getGenerators().size() > 0) {
    currentAiringChannelNumber = moduleModel.getGenerators().get(0).getStringParam(TP_CHANNEL_NUMBER) == null ? "" : moduleModel.getGenerators().get(0).getStringParam(TP_CHANNEL_NUMBER);
}

答案 2 :(得分:0)

“getGenerators()”中没有元素。

您可能必须验证元素是否存在。

尝试这样的事情

String currentAiringChannelNumber=moduleModel.getGenerators().isElementIndex(0) ? "" : moduleModel.getGenerators().get(0).getStringParam(TP_CHANNEL_NUMBER);

答案 3 :(得分:0)

似乎 getGenerator()在您的代码中返回列表。在此列表中使用get(0)之前,您需要确保其大小应大于0。

答案 4 :(得分:0)

你可以使用try-catch来处理抛出的异常。

使用以下代码:

    String currentAiringChannelNumber; //Declare String object
    try{ // Following block of code is ran, if an exception is thrown it will be caught and the the lines of code in the try block after the line of code that caused the exception to be thrown will not be run instead the code in the catch block will be ran.
        currentAiringChannelNumber = moduleModel.getGenerators().get(0).getStringParam(TP_CHANNEL_NUMBER);
    }
    catch(Exception e){ //Catching any exception thrown, accommodates for NullPointerException, IndexOutOfBoundsException as well as all other exceptions that are thrown. 
        currentAiringChannelNumber  = ""; //Code to handle predicted exceptions being thrown, which are the NullPointerException and IndexOutOfBoundsException.
    }

注意:无论在try块中执行代码时是否抛出异常,都将运行try-catch语句之后的代码。