ArrayList抛出IndexOutOfBoundsException的Set方法 [英] Set Method of ArrayList throwing IndexOutOfBoundsException

查看:36
本文介绍了ArrayList抛出IndexOutOfBoundsException的Set方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在处理 ArrayList 时,我发现在使用带有 initialCapacity 的构造函数设置数组的初始大小后,然后使用 set()尽管创建了数组,但抛出异常,但大小设置不正确.

While working on ArrayList, I found after setting the initial size of array using the constructor with initialCapacity, then use set() will throw an exception although the array is created, but size isn't set correctly.

使用 ensureCapacity() 也不起作用,因为它基于 elementData 数组而不是 size.

Using ensureCapacity() won't work either because it is based on the elementData array instead of size.

由于带有 ensureCapacity() 的静态 DEFAULT_CAPACITY,还有其他副作用.

There are other side effects because of the static DEFAULT_CAPACITY with ensureCapacity().

使这项工作起作用的唯一方法是在使用构造函数后根据需要多次使用 add().

The only way to make this work is to use add() as many time as required after using the constructor.

请检查下面的代码.

import java.util.ArrayList;
import java.util.List;

public class Test {

public static void main(String[] args) {

    List test = new ArrayList(10);
    test.set(5, "test");
    System.out.println(test.size());
}

我不知道为什么 java 会抛出这个异常.

I am not sure why java is throwing this exception.

我期望的行为:test.size() 应该返回 10 并且 set(5, ...) 应该可以工作.

Behaviour I expected: test.size() should return 10 and set(5, ...) should work.

实际:抛出异常IndexOutOfBoundsException.

那么是 set 方法导致了问题吗?

So is it set method that is causing problem ?

推荐答案

test.set(5, "test"); 是抛出这个异常的语句,因为你的 ArrayList 为空(size() 将返回 0 如果你得到那个语句),如果没有,你不能设置第 i 个元素已经包含一个值.您必须向 ArrayList 添加至少 6 个元素,才能使 test.set(5, "test"); 有效.

test.set(5, "test"); is the statement that throws this exception, since your ArrayList is empty (size() would return 0 if you got to that statement), and you can't set the i'th element if it doesn't already contain a value. You must add at least 6 elements to your ArrayList in order for test.set(5, "test"); to be valid.

new ArrayList(10) 不会创建大小为 10 的 ArrayList.它会创建一个初始容量为 10 的空 ArrayList.

new ArrayList(10) doesn't create an ArrayList whose size is 10. It creates an empty ArrayList whose initial capacity is 10.

这篇关于ArrayList抛出IndexOutOfBoundsException的Set方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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