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

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

问题描述

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.

那么设置方法会导致问题吗?

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.它会创建一个空的ArrayList,其初始容量为10.

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

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

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