-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.

3
  • If the List is empty you can't add an element at index 1. Use an array (you'll need to find the max offset first). Or a Map. Commented May 28, 2018 at 22:05
  • 2
    "Index: 1, Size: 0" -- that's all you need to know. Commented May 28, 2018 at 22:17
  • on that note, why are you using add(number, object) instead of just add(object)? Commented May 28, 2018 at 22:28

1 Answer 1

-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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.