Pregunta

Tengo esto:

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

Y arroja un ArrayIndexoUtofboundSexception.

No sé por qué. ¿Alguien podría ayudarme?

¿Fue útil?

Solución

No puedes configurar un elemento en un Vector o cualquier otro List Si ese índice ya no está ocupado. Mediante el uso new Vector<Node<Key, Elem>>(2) te aseguras de que el vector inicialmente tenga el capacidad para dos elementos, pero todavía está vacío y así getting o setEl uso de cualquier índice no funcionará.

En otras palabras, la lista no ha crecido lo suficientemente grande como para que ese índice sea válido todavía. Use esto en su lugar:

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

También podrías hacer:

this.leftRight.add(0, null);
this.leftRight.add(1, null);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top