【问题标题】:java.lang.IndexOutOfBoundsException in for each loop [duplicate]每个循环中的 java.lang.IndexOutOfBoundsException [重复]
【发布时间】:2018-11-07 11:46:56
【问题描述】:
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;
}

我得到以下异常:

线程“主”java.lang.IndexOutOfBoundsException 中的异常:索引: 1、大小:0 at java.util.ArrayList.rangeCheckForAdd(Unknown Source) 在 java.util.ArrayList.add(Unknown Source)

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

谁能帮我解决这个问题?提前致谢。

【问题讨论】:

  • 如果List 为空,则无法在索引1 处添加元素。使用数组(您需要先找到最大偏移量)。或Map
  • “索引:1,大小:0”——这就是您需要知道的全部内容。
  • 在那张纸条上,你为什么使用add(number, object) 而不仅仅是add(object)

标签: java indexoutofboundsexception


【解决方案1】:

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

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

在你的情况下 index == 1size() 返回 0 因为 dispatchTable 列表仍然空。

你最好改变这个:

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));
    }
}

到这里:

    List<String> superDispatchTable = superEntry != null ? getDispatchTable(superEntry.getOffset()) : Collections.EMPTY_LIST;
    List<String> dispatchTable = new ArrayList<>(superDispatchTable);

【讨论】:

    猜你喜欢
    • 2021-08-27
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 2015-05-11
    • 2017-12-22
    相关资源
    最近更新 更多