Kris
Kris

Reputation: 3769

Android: Specify array size?

anyone knows how to specify array size?

public String[] videoNames = {""}

the array above can accomodate only one value. i want to extend how many values this array can accomodate.

Upvotes: 2

Views: 15113

Answers (5)

Rudy
Rudy

Reputation: 7044

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(""); 
}

Upvotes: 4

Prince John Wesley
Prince John Wesley

Reputation: 63698

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");

Upvotes: 2

Harinder
Harinder

Reputation: 11944

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

Upvotes: 1

Sunil Kumar Sahoo
Sunil Kumar Sahoo

Reputation: 53667

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

How to add elements to array list

Thanks Deepak

Upvotes: 2

wired00
wired00

Reputation: 14468

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));
}

Upvotes: 3

Related Questions