2012-03-12 18 views
1

时,我有此数组:Java的ArrayList的OutofBounds添加一项

ArrayList<Problem> problems = new ArrayList <Problem>(100); 

然后我尽量让物体摆在它:

Problem p = new Problem(); 
p.setProblemName("Some text"); 

然后我尝试将对象添加到阵列:

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.为什么会发生此错误?看来这是非常直截了当的。

谢谢!

回答

2

您不使用set添加到ArrayList您使用它来覆盖现有的元素。

problems.set(1, p); //Overwrite the element at position 1 

您使用add

problems.add(p); 

将在年底

problems.add(1, p); 

添加它会在索引1添加它,这将抛出IndexOutOfBoundsException异常的
指数< 0或指数>ArrayList.size()。这将是第一次尝试添加的情况。

也只是为你的知识

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

ArrayList#set()

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

size()返回在数组列表,而不是容量元素的个数。

1

当你写ArrayList<Problem> problems = new ArrayList <Problem>(100);,你只能告诉的Java,你认为你要使用那种能力(从而优化底层数组的大小),但列表中仍然有一个大小为0

你需要使用add()

problems.add(p); 

会在第一位加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 
0

则应该这样写:

problems.add(0, p); 

你没有,你要插入峰值到第一名任何零成员!

+2

设置将不起作用。 ArrayList没有任何元素,所以Size = 0。如果索引> = size,则设置throws和IndexOfOutBoundsException。 – twain249 2012-03-12 19:06:43

+0

他会得到相同的异常... – assylias 2012-03-12 19:06:45

+0

谢谢,我的意思是添加,我的重点是索引:D – 2012-03-12 19:22:32

-1

尝试

problems.set(0, p); 

阵列中的第一位置始终为0

编辑你应该使用。新增()方法将对象添加到数组虽然

+0

当我将它设置为0,我得到此错误:java.lang.IndexOutOfBoundsException:索引0无效,大小为0 – GeekedOut 2012-03-12 19:07:34

+0

如果列表中没有元素,设置将不起作用。他必须使用添加。在索引<0 ||中设置失败index> = size'。大小= 0设置总是失败。 – twain249 2012-03-12 19:08:36