简体   繁体   中英

Java holding 3 values in array

I need a array object, that should holds 3 Objects.

At first was using Collection , but I need to add to a specific place. for example:

CollectionObject.add(pos, myObject)

Then I went to ArrayList , created object like this:

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:

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? Are there any better array holding objects, like Vector or something?

Use an array of 3 elements instead as follows:

MyObject [] array = new MyObject[3];
array[2] = myObject;

ArrayList is not an array, it is a List implemented using a hidden array. 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. 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM