add item to the array of string dynamically

J

jrefactors

I want to ask if we can add item to the array of strings dynamically?

String[] s = {"Joe","John","May"};

If I want to add another name called "Tim", how to do that?
 
K

kjc

I want to ask if we can add item to the array of strings dynamically?

String[] s = {"Joe","John","May"};

If I want to add another name called "Tim", how to do that?
You can't add anything more to the definition (s) above.
You've defined s to a fixed size of 3 String objects.
Why not just use an ArrayList.
 
K

klynn47

No, you cannot change the array's size once it's created.

You can, however, achieve what you want to do with the following.

Create a new String array with enough space to hold the current
contents of the array referred to by s and 1 more.

String[] temp = new String[s.length+1];

Copy the contents of the array referred to by s into the first part of
the new array.

System.arraycopy(s,0,temp,0,s.length);

Place the new element into the last position in temp.

temp[s.length] = "Tim";

Now rearrange s to point to the same array that temp refers to.

s = temp;

The original array that was referred to by s is now elegible for
garbage collection.
 
K

kjc

No, you cannot change the array's size once it's created.

You can, however, achieve what you want to do with the following.

Create a new String array with enough space to hold the current
contents of the array referred to by s and 1 more.

String[] temp = new String[s.length+1];

Copy the contents of the array referred to by s into the first part of
the new array.

System.arraycopy(s,0,temp,0,s.length);

Place the new element into the last position in temp.

temp[s.length] = "Tim";

Now rearrange s to point to the same array that temp refers to.

s = temp;

The original array that was referred to by s is now elegible for
garbage collection.
ArrayList looking better by the second.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,169
Latest member
ArturoOlne
Top