Matt
Matt

Reputation: 482

Out of bounds but it shouldn't

public class Ctrl {

    Graph g = new Graph(); 
    Edge[] edges = new Edge[g.getM()];
    int[] verteY = new int[g.getM()];
    int[] verteX = new int[g.getM()];
    int[] vCost = new int[g.getM()];
    int contor=0;

    public void add(int x,int y,int c) {
        System.out.println("contor:" + this.contor);
        System.out.println("M:" + g.getM());
        verteX[this.contor] = x;
        verteY[this.contor] = y;
        vCost[this.contor] = c;
        this.contor = this.contor + 1;
}

and the output is

contor:0
M:5

why do I get java.lang.ArrayIndexOutOfBoundsException: 0 then?

Upvotes: 0

Views: 58

Answers (1)

NPE
NPE

Reputation: 500167

It seems likely that a newly-initalized Graph's getM() returns zero, making all four arrays zero-size.

If g.getM() later changes, the arrays don't automatically get resized.

My recommendation would be to use ArrayList instead of raw arrays. This would make it easy to append to them.

Upvotes: 3

Related Questions