如何动态添加元素到String数组?

ome*_*erk 53 java arrays string arraylist

现在我有一个字符串数组__CODE__.

我想在for循环中向this数组添加元素.但我没有办法.我是Java和android的新手.

Jav*_*ave 109

Arrays在Java中有一个已定义的大小,以后你不能通过添加或删除元素来更改它(你可以在这里阅读一些基础知识).

相反,使用List:

ArrayList<String> mylist = new ArrayList<String>();
mylist.add(mystring); //this adds an element to the list.
Run Code Online (Sandbox Code Playgroud)

当然,如果您事先知道要在数组中放入多少个字符串,则可以创建该数组的数组并使用正确的位置设置元素:

String[] myarray = new String[numberofstrings];
myarray[23] = string24; //this sets the 24'th (first index is 0) element to string24.
Run Code Online (Sandbox Code Playgroud)


Ris*_*han 24

使用String数组时,必须在初始化时给出数组大小

例如

String[] str = new String[10];
Run Code Online (Sandbox Code Playgroud)

您可以使用索引0-9来存储值

str[0] = "value1"
str[1] = "value2"
str[2] = "value3"
str[3] = "value4"
str[4] = "value5"
str[5] = "value6"
str[6] = "value7"
str[7] = "value8"
str[8] = "value9"
str[9] = "value10"
Run Code Online (Sandbox Code Playgroud)

如果你正在使用字符串数组的ArrayList instread,你可以使用它而无需初始化数组的大小ArrayList str = new ArrayList();

你可以使用Arraylist的add方法来增加价值

str.add("Value1");
Run Code Online (Sandbox Code Playgroud)

从arraylist中获取值,可以使用get方法

String s = str.get(0);
Run Code Online (Sandbox Code Playgroud)

尺寸方法查找项目总数

int nCount = str.size();
Run Code Online (Sandbox Code Playgroud)

这里了解更多