0

I have an Array with Defualt "Cat", "Dog, "Simon", "Smith" the length is therefore 3.

If I want to edit smith I type array[3] = "JR Smith"

but if user want to add another thing to the array I tried: array[4] = "Car" But it gave me out of bounds.

How do I extend an array outside it's initialization?

//Simon

EDIT*

Ye I know there is List. But isnt there a way with array. becuase it took me ages to write like 200 length array...

6 Answers 6

8

You can not extend an array outside its initialization. For such a purpose use of an ArrayList is advised. It has the property to grow beyond its predefined size.

A simple example of using ArrayList can be found here

0
2

You should use a list. Arrays are not dynamic in java :

 import java.util.*;

 List<String> list = new ArrayList<String>();
 list.add( "cat" ); 
 list.add( "dog" ); 
 list.add( "bird" ); 
 //later
 list.add( "car" );
2

I suggest using ArrayList. You can always convert the ArrayList to an array using the toArray() method.

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html#toArray%28%29

1

There is kind of a way to enlarge an array:

int[] array = { 1, 2, 3 };
int[] newArray = new int[5];
System.arraycopy(array, 0, newArray, 0, array.length);
array = newArray;
array[4] = 5;

array is now { 1, 2, 3, 0, 5 }

You create a bigger one, copy the old one into the new one and use the new one. That's also what ArrayList does internally.

0

Try using ArrayList instead. Once you initialize an array you cant change its size, unless of course you re-initialize it.

See here Java dynamic array sizes?

0

My personal favorite way is to import java.util.Arrays and then use something along the lines of:

List tempList = Arrays.asList(yourArray)
tempList.add(whateverYouWant)
yourArray = tempList.toArray();

First line converts your array to a List, second adds to the list, and the third changes it back.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.