2

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.

5 Answers 5

4

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(""); 
}
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

2

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

How to add elements to array list

Thanks Deepak

Comments

2

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

3 Comments

Hi @John, thanks for your response. But how can I use an array list and how can I initialize an array properly coz when I initialize the array to null, my code returns nullPointerException... Sorry for the noob question
Is there a way to specify unlimited array size?
@Kris: then use ArrayList class.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.