Why am I getting “ArrayIndexOutOfBoundsException: 0”? (array of string)

85 Views Asked by At

I have in my code a procedure like this:

public void setawal(ArrayList<String> edge, String[] nodeforsub, int sizes){
    size=sizes;
    jumedge=new String[size];
    totalsubedge=new String[size];
    hasiljumedge=new String[size];
    hasilsubedge=new String[size];
    for(int j=0;j<edge.size();j++){
        if(jumedge[0]==null){
            jumedge[0]=edge.get(j);
        }else{
            jumedge[0]=jumedge[0]+":"+edge.get(j);
        }
    }
    urutan=new int[edge.size()];
    for(int i=0;i<edge.size();i++){
        urutan[i]=i;
    }
    node=nodeforsub;
    getsub(size, node, jumedge, totalsubedge, hasilsubedge, urutan);
}

in my project, two classes will access this procedure, when the first class accesses this procedure it works properly, but when the second class accesses this procedure, it showed this error message:

java.lang.ArrayIndexOutOfBoundsException: 0

How can I fix it?

I know the problem is when the second class tries to access jumedge[0], but I am confused why for first class it can access it properly?

1

There are 1 best solutions below

0
Eran On BEST ANSWER

The length of the jumedge array depends on the value of the sizes parameter passed to setawal. If you are passing 0, the array will be empty and jumedge[0] will throw the exception.

This explains why some calls to this method throw an exception while others don't.

BTW, if you are only using the first element of the jumedge array, you don't need it to be an array. A single String will suffice. I don't know what the getsub method does with the jumedge array, but since you only set jumedge[0], you can pass a single String to that method.