2009-07-27

java Add item to the array of string dynamically

add item to the array of string dynamically

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.

0 留言: