首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >java.lang.IndexOutOfBoundsException in for each循环

java.lang.IndexOutOfBoundsException in for each循环
EN

Stack Overflow用户
提问于 2018-05-29 06:03:52
回答 1查看 863关注 0票数 -1
代码语言:javascript
复制
public String codeGeneration() { 

    ArrayList<String> dispatchTable = new ArrayList<String>();

    if(superEntry != null) { 
        ArrayList<String> superDispatchTable = getDispatchTable(superEntry.getOffset());

        for(int i = 0; i < superDispatchTable.size(); i++) {
            dispatchTable.add(i, superDispatchTable.get(i));
        }
    }

    String methodsCode = "";

    for(Node m : methods) {
        methodsCode+=m.codeGeneration();
        MethodNode mnode = (MethodNode) m;
        dispatchTable.add(mnode.getOffset(), mnode.getLabel());
    }
    addDispatchTable(dispatchTable);

    String codeDT = "";
    for(String s : dispatchTable) {
        codeDT+= "push " + s + "\n"
                + "lhp\n"
                + "sw\n" 
                + "lhp\n"
                + "push 1\n"
                + "add\n"
                + "shp\n"; 
    }

    return "lhp\n"
    + codeDT;
}

我得到了以下异常:

线程"main“中的

异常java.lang.IndexOutOfBoundsException:索引: 1,大小:0位于java.util.ArrayList.rangeCheckForAdd(未知源)的java.util.ArrayList.add(未知源)

导致错误的行是:dispatchTable.add(mnode.getOffset(), mnode.getLabel());

有人能帮我解决这个问题吗?提前谢谢。

EN

回答 1

Stack Overflow用户

发布于 2018-05-29 06:56:59

引用List#void add(int index, E element)的javadoc

代码语言:javascript
复制
Throws:
...
IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())

在本例中,索引== 1size()返回,因为dispatchTable列表仍然为空。

你最好改变这一点:

代码语言:javascript
复制
ArrayList<String> dispatchTable = new ArrayList<String>();

if(superEntry != null) { 
    ArrayList<String> superDispatchTable = getDispatchTable(superEntry.getOffset());

    for(int i = 0; i < superDispatchTable.size(); i++) {
        dispatchTable.add(i, superDispatchTable.get(i));
    }
}

要这样做:

代码语言:javascript
复制
    List<String> superDispatchTable = superEntry != null ? getDispatchTable(superEntry.getOffset()) : Collections.EMPTY_LIST;
    List<String> dispatchTable = new ArrayList<>(superDispatchTable);
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50573884

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档