如何在Java中增加数组的大小? [英] How to increase the size of an array in Java?
问题描述
我想将用户所需的元素存储在一个数组中.但是我该怎么做.
I want to store as many elements as desired by the user in an array. But how do I do it.
如果我要创建一个数组,我必须使用固定的大小.每次将新元素添加到数组并且数组变满时,我都想将其大小更新为1".
If I were to create an array, I must do so with a fixed size. Every time a new element is added to the array and the array becomes full, I want to update its size by '1'.
我厌倦了各种类型的代码,但没有奏效.
I tired various types of code, but it did not work out.
如果有人能给我一个解决方案 - 如果可能的话,在代码中会很有帮助.
It would be of great help if someone could give me a solution regarding it - in code if possible.
推荐答案
不要使用数组,而是使用 java.util.List
的实现,例如 ArrayList
.ArrayList 有一个数组后端,它保存列表中的值,但数组大小由列表自动处理.
Instead of using an array, use an implementation of java.util.List
such as ArrayList
. An ArrayList has an array backend which holds values in a list, but the array size is automatically handles by the list.
ArrayList<String> list = new ArrayList<String>();
list.add("some string");
对于其他元素类型,您还可以使用 list.toArray(new String[list.size()])
等将列表转换为数组.
You can also convert the list into an array using list.toArray(new String[list.size()])
and so forth for other element types.
这篇关于如何在Java中增加数组的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!