初始化Vector上的ArrayIndexOutOfBoundsException [英] ArrayIndexOutOfBoundsException on a initialized Vector

查看:458
本文介绍了初始化Vector上的ArrayIndexOutOfBoundsException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:

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

并抛出ArrayIndexOutOfBoundsException。

and it throws an ArrayIndexOutOfBoundsException.

我不知道为什么。有人可以帮帮我吗?

I don't know why. Could someone help me?

推荐答案

你不能在 Vector 或任何其他列表如果该索引尚未被占用。通过使用 new Vector< Node< Key,Elem>>(2),您确保向量最初具有两个元素的容量 ,但它仍然是空的,所以获取 ting或设置使用任何索引都不会起作用。

You can't set an element in a Vector or any other List if that index isn't already occupied. By using new Vector<Node<Key, Elem>>(2) you're ensuring that the vector initially has the capacity for two elements, but it is still empty and so getting or setting using any index won't work.

换句话说,该列表还没有大到足以使该索引有效。改为使用:

In other words, the list hasn't grown big enough for that index to be valid yet. Use this instead:

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

你也可以这样做:

this.leftRight.add(0, null);
this.leftRight.add(1, null);

这篇关于初始化Vector上的ArrayIndexOutOfBoundsException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆