java Android:指定数组大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6175241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 14:41:12  来源:igfitidea点击:

Android: Specify array size?

javaandroidarrays

提问by Kris

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.

上面的数组只能容纳一个值。我想扩展这个数组可以容纳多少个值。

回答by Rudy

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

回答by wired00

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

如果你想要动态大小,那么使用arraylist。就像是:

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

回答by Sunil Kumar Sahoo

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

如果要动态添加元素,请使用 ArrayList。数组本质上是静态的。

How to add elements to array list

如何将元素添加到数组列表

Thanks Deepak

谢谢迪帕克

回答by Prince John Wesley

Use as:

用于:

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

or use ArrayListfor resizable array implementation.

或使用ArrayList实现可调整大小的数组。



EDIT: and initialize it like this:

编辑:并像这样初始化它:

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


With ArrayList:

使用ArrayList

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

回答by Harinder

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

如果您想使用在您的 commnet 中编写的数组列表,这里是一个数组列表

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

2 是你的字符串索引