[英]Java holding 3 values in array
I need a array object, that should holds 3 Objects. 我需要一个数组对象,该对象应该包含3个对象。
At first was using Collection
, but I need to add to a specific place. 起初使用Collection
,但是我需要添加到特定位置。 for example: 例如:
CollectionObject.add(pos, myObject)
Then I went to ArrayList
, created object like this: 然后我去了ArrayList
,创建了这样的对象:
ArrayList<MyObject> array = new ArrayList<MyObject>();
When creating this, it creats array with size 1, but I need to add to position 0-2, so adding like: 创建此数组时,它将创建大小为1的数组,但是我需要添加到位置0-2,因此添加如下内容:
array.add(2, myObject)
I got : 我有 :
java.lang.IndexOutOfBoundsException: Index: 2, Size: 1
My solution is, create arraylist, add 3 empty objects to it, and later overwrite, but any more subtle solution? 我的解决方案是,创建arraylist,向其中添加3个空对象,然后覆盖,但是还有其他更细微的解决方案吗? Are there any better array holding objects, like Vector
or something? 有没有更好的数组保存对象,例如Vector
或其他东西?
Use an array of 3 elements instead as follows: 改为使用3个元素组成的数组,如下所示:
MyObject [] array = new MyObject[3];
array[2] = myObject;
ArrayList
is not an array, it is a List
implemented using a hidden array. ArrayList
不是数组,它是使用隐藏数组实现的List
。 You need to add three items to it before you can address items by index, like this: 您需要先添加三个项目,然后才能按索引对项目进行寻址,如下所示:
ArrayList<MyObject> array = new ArrayList<MyObject>(3);
array.add(null);
array.add(null);
array.add(null);
array.set(2, myObject)
ArrayList
s grow automatically. ArrayList
会自动增长。 If you do not need this functionality, you use a plain array, for example, like this: 如果不需要此功能,则可以使用一个普通数组,例如:
MyObject array = new MyObject[] {myObject1, myObject2, myObject3};
Now you can replace items by using the indexing operator: 现在,您可以使用索引运算符替换项目:
array[2] = newMyObject;
MyObject[] a = new MyObject[3];
a[2] = new MyObject();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.