gpt4 book ai didi

java - 如何动态地将元素添加到字符串数组?

转载 作者:IT老高 更新时间:2023-10-28 20:33:01 25 4
gpt4 key购买 nike

我想从 for 循环中向字符串数组中添加动态数量的元素。

如何创建一个未定义长度的字符串数组?

最佳答案

Java 中的

Arrays 具有定义的大小,以后无法通过添加或删除元素来更改它(您可以阅读一些基础知识 here )。

改为使用 List :

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

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

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

关于java - 如何动态地将元素添加到字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15039519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com