How to add new elements to an array? How to add new elements to an array? arrays arrays

How to add new elements to an array?


The size of an array can't be modified. If you want a bigger array you have to instantiate a new one.

A better solution would be to use an ArrayList which can grow as you need it. The method ArrayList.toArray( T[] a ) gives you back your array if you need it in this form.

List<String> where = new ArrayList<String>();where.add( ContactsContract.Contacts.HAS_PHONE_NUMBER+"=1" );where.add( ContactsContract.Contacts.IN_VISIBLE_GROUP+"=1" );

If you need to convert it to a simple array...

String[] simpleArray = new String[ where.size() ];where.toArray( simpleArray );

But most things you do with an array you can do with this ArrayList, too:

// iterate over the arrayfor( String oneItem : where ) {    ...}// get specific itemswhere.get( 1 );


Use a List<String>, such as an ArrayList<String>. It's dynamically growable, unlike arrays (see: Effective Java 2nd Edition, Item 25: Prefer lists to arrays).

import java.util.*;//....List<String> list = new ArrayList<String>();list.add("1");list.add("2");list.add("3");System.out.println(list); // prints "[1, 2, 3]"

If you insist on using arrays, you can use java.util.Arrays.copyOf to allocate a bigger array to accomodate the additional element. This is really not the best solution, though.

static <T> T[] append(T[] arr, T element) {    final int N = arr.length;    arr = Arrays.copyOf(arr, N + 1);    arr[N] = element;    return arr;}String[] arr = { "1", "2", "3" };System.out.println(Arrays.toString(arr)); // prints "[1, 2, 3]"arr = append(arr, "4");System.out.println(Arrays.toString(arr)); // prints "[1, 2, 3, 4]"

This is O(N) per append. ArrayList, on the other hand, has O(1) amortized cost per operation.

See also


Apache Commons Lang has

T[] t = ArrayUtils.add( initialArray, newitem );

it returns a new array, but if you're really working with arrays for some reason, this may be the ideal way to do this.