添加项时Java ArrayList OutofBounds

添加项时Java ArrayList OutofBounds,java,arraylist,Java,Arraylist,我有这个阵列: ArrayList<Problem> problems = new ArrayList <Problem>( 100 ); 然后我尝试将对象添加到数组中: problems.set(1, p); 但此时系统会抛出一个运行时异常: 03-12 18:58:04.573: E/AndroidRuntime(813): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 1, size

我有这个阵列:

ArrayList<Problem> problems = new ArrayList <Problem>( 100 );
然后我尝试将对象添加到数组中:

problems.set(1, p);
但此时系统会抛出一个运行时异常:

03-12 18:58:04.573: E/AndroidRuntime(813): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
但是如果我将数组的初始大小增加到100。为什么会发生这种错误?这似乎是非常直截了当的

谢谢

ArrayList#set()

抛出:
IndexOutOfBoundsException
-如果索引超出范围
(索引<0 | |索引>=size())

size()

抛出:
IndexOutOfBoundsException
-如果索引超出范围
(索引<0 | |索引>=size())


size(),您只告诉Java您认为您将使用这种容量(它优化了底层数组的大小),但列表的大小仍然是0

您需要使用
add()

将在第一个位置添加p

List<Problem> problems = new ArrayList <Problem>();
Problem p = new Problem ();
p.setProblemName( "Some text" );

problems.add(p);

Problem p2 = problems.get(0); //p2 == p
List problems=newarraylist();
问题p=新问题();
p、 setProblemName(“某些文本”);
添加(p);
问题p2=问题。获取(0)//p2==p

当您编写
ArrayList时,问题=新建ArrayList(100),您只告诉Java您认为您将使用这种容量(它优化了底层数组的大小),但列表的大小仍然是0

您需要使用
add()

将在第一个位置添加p

List<Problem> problems = new ArrayList <Problem>();
Problem p = new Problem ();
p.setProblemName( "Some text" );

problems.add(p);

Problem p2 = problems.get(0); //p2 == p
List problems=newarraylist();
问题p=新问题();
p、 setProblemName(“某些文本”);
添加(p);
问题p2=问题。获取(0)//p2==p

您应该写以下内容:

problems.add(0, p);

您没有任何第0个成员希望将p插入第一位

您应该写以下内容:

problems.add(0, p);

您没有任何第0个成员希望将p插入第一位

您没有使用
set
添加到
ArrayList
中,而是使用它覆盖现有元素

problems.set(1, p); //Overwrite the element at position 1 
您可以使用
add

problems.add(p); 
将在末尾添加它

problems.add(1, p);
将它添加到索引1,这将为
索引<0或索引>
ArrayList.size()
引发IndexOutOfBoundsException。这将是首次尝试添加时的情况

也只是为了你的知识

problems.add(ArrayList.size(), p); //Works the same as problems.add(p);

您不会使用
set
来添加到
ArrayList
中,而是使用它来覆盖现有元素

problems.set(1, p); //Overwrite the element at position 1 
您可以使用
add

problems.add(p); 
将在末尾添加它

problems.add(1, p);
将它添加到索引1,这将为
索引<0或索引>
ArrayList.size()
引发IndexOutOfBoundsException。这将是首次尝试添加时的情况

也只是为了你的知识

problems.add(ArrayList.size(), p); //Works the same as problems.add(p);
试一试

数组中的第一个位置始终为0

编辑您应该使用.add()方法将对象添加到数组中,但请尝试

数组中的第一个位置始终为0


编辑您应该使用.add()方法将对象添加到数组中,但设置不起作用。
ArrayList
还没有元素,因此Size=0。如果索引大于等于大小,则设置抛出和IndexOfOutBoundsException。设置将不起作用。
ArrayList
还没有元素,因此Size=0。如果索引大于等于size,则Set抛出和IndexOfOutBoundsException。当我将其设置为0时,会出现以下错误:java.lang.indexoutboundsException:索引0无效,size为0如果列表中没有元素,Set将不起作用。他必须使用add。设置在
索引<0 | |索引>=size
中失败。设置大小为0时总是失败。当我将其设置为0时,会出现以下错误:java.lang.IndexOutOfBoundsException:索引0无效,如果列表中没有元素,则设置大小为0将不起作用。他必须使用add。设置在
索引<0 | |索引>=size
中失败。设置大小为0时总是失败。