使用java.util.Vector的IndexOutOfBoundException

时间:2015-05-05 04:42:59

标签: java arrays dynamic vector indexoutofboundsexception

使用java.util.Vectorjava.util.ArrayList.时遇到问题 我知道在向量中保存多少元素的容量或更好。所以我使用构造函数java.util.List的实现来初始化new Vector<?>(int capacity)

在初始化List之后,我使用了set(index, value)方法,但此调用会产生IndexOutOfBoundException。这很令人困惑,因为我使用构造函数将容量设置为给定值。

以下代码段显示了问题:

  public void calculateSimple(List<Stock> values, int n) {

    if (n<=0) {
        throw new IllegalArgumentException("N must not be zero or negativ");
    }       

    int max = values.size();

    result = new Vector<Double>(max);

    System.out.println("Size of result "+result.size());

    if (max == 0) {
        result.add(0.0);
    }

    if (max <= n) {
        n = max;
    }

    for (int i = 1; i <= n; i++) {          
        List<Double> subList = values.subList(max-i-n, max-i);
        result.set(result.size()-i, calculateSimpleValue(subList, n));
    }   
}

我知道我可以使用简单的数组来解决这个问题。我想问一下代码中是否有任何错误,或者我对容量构造函数有一些错误的想法,关于类Vector或任何其他List实现。

更新

问题是: 是否可以以混合方式使用任何类型的java.util数据结构 (数组,动态列表(或任何其他))

3 个答案:

答案 0 :(得分:4)

如果你想创建一个用一些值初始化的列表,比如0.0或null,这是一个快速的方法:

ArrayList<Double> list = new ArrayList<>(Collections.nCopies(100, value));

答案 1 :(得分:1)

从java.util.Vector.set()方法我可以看到

 /**
     * Replaces the element at the specified position in this Vector with the
     * specified element.
     *
     * @param index index of the element to replace
     * @param element element to be stored at the specified position
     * @return the element previously at the specified position
     * @throws ArrayIndexOutOfBoundsException if the index is out of range
     *         ({@code index < 0 || index >= size()})
     * @since 1.2
     */
    public synchronized E set(int index, E element) {
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

因此,当您使用set方法时,在实例化向量时,构造函数中的result.size()-i >= calculateSimpleValue(subList, n)。{elementCount = elementdata.length可能会出现。

答案 2 :(得分:-1)

在上面的示例中,您使用了子列表方法的点,如果max = n那么在这种情况下它将导致负值,这也可能导致IndexOutOfBoundException

相关问题