Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add new elements to an array?

I have the following code:

String[] where; where.append(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1"); where.append(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1"); 

Those two appends are not compiling. How would that work correctly?

like image 541
Pentium10 Avatar asked May 16 '10 10:05

Pentium10


People also ask

How do you add elements to an array in C++?

Algorithm. Step 1 : For i from 0 to n-1, follow step 2 ; Step 2 : sum = sum + arr[i] Step 3 : print sum.


1 Answers

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 array for( String oneItem : where ) {     ... }  // get specific items where.get( 1 ); 
like image 90
tangens Avatar answered Oct 01 '22 02:10

tangens