Domanda

ho questo:

public class DoubleList<Key, Elem> implements ADTDoubleList<Key, Elem> {

    private Vector<Node<Key, Elem>> leftRight = new Vector<Node<Key, Elem>>(2);
    private int[] numLeftNumRight = new int[2];

    public DoubleList() {
        this.leftRight.set(0, null);
        this.leftRight.set(1, null);
        this.numLeftNumRight[0] = 0;
        this.numLeftNumRight[1] = 0;
    }
}

e viene generata ArrayIndexOutOfBoundsException.

Non so perché. Potrebbe qualcuno aiutarlo?

È stato utile?

Soluzione

Non è possibile impostare un elemento in un Vector o qualsiasi altro List se questo indice non è già occupato. Utilizzando new Vector<Node<Key, Elem>>(2) si sta assicurando che il vettore ha inizialmente il capacità per due elementi, ma è ancora vuoto e così getting o setting utilizzando qualsiasi indice non funziona.

In altre parole, la lista non è cresciuta abbastanza grande per tale indice sia ancora valido. Utilizzare questo, invece:

this.leftRight.add(null);  //index 0
this.leftRight.add(null);  //index 1

Si potrebbe anche fare:

this.leftRight.add(0, null);
this.leftRight.add(1, null);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top