Java 如何增加数组列表的大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19991217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to increase the size of an arraylist
提问by KoolAid
I'm trying to increase the size of an array list but it doesnt seem to want to work.
我正在尝试增加数组列表的大小,但它似乎不想工作。
I am doing this:
我正在这样做:
final int QUEUE_CAPACITY = 27;
ArrayList adjacencyList = new ArrayList<Integer>(QUEUE_CAPACITY);
But when I try to add something with the add that has two paramters, (index,value) I get this error:
但是,当我尝试使用具有两个参数 (index,value) 的 add 添加某些内容时,出现此错误:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
采纳答案by rgettman
You have established the initial capacity of the ArrayList
, but there are still no items in the list. You can't insert an item before index 1 if it doesn't exist yet.
您已经建立了 的初始容量ArrayList
,但列表中仍然没有项目。如果尚不存在,则不能在索引 1 之前插入项目。
You must use the one-argument add
methodto append to the end of the list, or supply 0
as the index in the two-argument add
method, so that there is something in the list.
回答by Josh
Are you calling the equivalent of adjacencyList.add(1, 1)
? If so, you're trying to add to an empty list at index 1
, which doesn't exist. Just call adjacencyList.add(<value>)
.
你打电话相当于adjacencyList.add(1, 1)
?如果是这样,您正在尝试添加到 index 处的空列表中1
,该列表不存在。就打电话adjacencyList.add(<value>)
。
Also, include the generic type at initialization:
此外,在初始化时包括泛型类型:
ArrayList<Integer> adjacencyList = new ArrayList<Integer>(QUEUE_CAPACITY);
PS. You don't usually need to adjust the initial capacity of an ArrayList
unless you know the list will rarely end up being small.
附注。您通常不需要调整 a 的初始容量,ArrayList
除非您知道该列表最终很少会变小。
回答by yamafontes
That's not how it works.
这不是它的工作原理。
If you're going to insert something at a certain position, you need to have elements stored up to the point in the list already.
如果您要在某个位置插入一些东西,您需要已经将元素存储到列表中的那个点。
回答by Linus
Well, If you really want to do this.
好吧,如果你真的想这样做。
You need to Intialise the Array with 'Integers' like '0' or so and then instead of add() method use the set(int index, E element) method which Replaces the element at the specified position in this list with the specified element.
您需要使用“整数”(如“0”左右)初始化数组,然后使用 set(int index, E element) 方法代替 add() 方法,该方法用指定的元素替换此列表中指定位置的元素.
Any index at which you see '0' is equivalent to empty.
您看到“0”的任何索引都相当于空。