开发者

Android: Specify array size?

anyone knows how to specify array size?

public String[] videoNames = {""}

the array above ca开发者_运维百科n accomodate only one value. i want to extend how many values this array can accomodate.


You should write it like this.

String[] videoNames = new String[5]; // create videoNames array with length = 5
for(int i=0;i<videoNames.length();i++)
{
   // IMPORTANT : for each videoName, instantiate as new String.
   videoNames[i] = new String(""); 
}


if you want dynamic size then use arraylist. something like:

public ArrayList<String> myList = new ArrayList<String>();

...

myList.add("blah");

...

for(int i = 0, l = myList.size(); i < l; i++) {
  // do stuff with array items
  Log.d("myapp", "item: " + myList.get(i));
}


Use ArrayList if you want to add elements dynamically. Array is static in nature.

How to add elements to array list

Thanks Deepak


Use as:

public String[] videoNames = new String[SIZE]; // SIZE is an integer

or use ArrayList for resizable array implementation.


EDIT: and initialize it like this:

int len = videoNames.length();
for(int idx = 0; idx < len; idx++) {
   videoNames[idx] = ""; 
}

With ArrayList:

ArrayList<String> videoNames = new ArrayList<String>();
// and insert 
videoNames.add("my video");


If you want to use an arraylist as written in your commnet here is an arraylist

ArrayList<String> videoNames =new ArrayList<String>();

add as many as you want no need to give size

    videoNames.add("yourstring");
videoNames.add("yourstring");
videoNames.add("yourstring");
videoNames.add("yourstring");

to empty the list

 videoNames.clear();

to get a string use

String a=videoNames.get(2);

2 is your string index

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜