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

I get the following exception:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0 at java.util.ArrayList.rangeCheckForAdd(Unknown Source) at java.util.ArrayList.add(Unknown Source)

The line which causes the error is: dispatchTable.add(mnode.getOffset(), mnode.getLabel());

Can anyone help me solve this? Thanks in advance.

Jan B.
  • 6,030
  • 5
  • 32
  • 53

1 Answers1

-1

Quote from the javadoc of List#void add(int index, E element)

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

In your case index == 1 and size() returns 0 because the dispatchTable list is still empty.

You better to change this:

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

to this:

    List<String> superDispatchTable = superEntry != null ? getDispatchTable(superEntry.getOffset()) : Collections.EMPTY_LIST;
    List<String> dispatchTable = new ArrayList<>(superDispatchTable);
Rostislav Krasny
  • 577
  • 3
  • 14