如何动态地向String数组添加元素? [英] How to dynamically add elements to String array?

查看:54
本文介绍了如何动态地向String数组添加元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to add dynamic number of elements to a string array from inside a for loop.

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

How to create an string array of an undefined length?

推荐答案

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

Arrays in Java have a defined size, you cannot change it later by adding or removing elements (you can read some basics here).

相反,使用 List:

Instead, use a List:

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

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

Of course, if you know beforehand how many strings you are going to put in your array, you can create an array of that size and set the elements by using the correct position:

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

这篇关于如何动态地向String数组添加元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆