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...

Bob Kaufman
  • 12,864
  • 16
  • 78
  • 107
AndroidXTr3meN
  • 399
  • 2
  • 9
  • 19

6 Answers6

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

Anurag Ramdasan
  • 4,189
  • 4
  • 31
  • 53
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" );
Snicolas
  • 37,840
  • 15
  • 114
  • 173
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

Wojciech Górski
  • 945
  • 11
  • 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.

zapl
  • 63,179
  • 10
  • 123
  • 154
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?

Community
  • 1
  • 1
Rob
  • 23
  • 5
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.

AegisHexad
  • 2,164
  • 1
  • 11
  • 11