java 动态数组列表大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11001859/
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-31 03:22:03  来源:igfitidea点击:

Dynamic Array List size

javaarraysdynamic

提问by Yuzakii

How can I set size of a dynamic array with Java?

如何使用 Java 设置动态数组的大小?

I tried setsize(...)with the array variable but not working. How can I do this?

我尝试setsize(...)使用数组变量但不起作用。我怎样才能做到这一点?

回答by Jigar Joshi

array size needs to be fixed while initialization, use Listinstead and then have array from Listusing toArray()

数组大小需要被固定,而初始化,使用List代替,然后有阵列从List使用toArray()

For example:

例如:

List<Integer> listOfInt = new ArrayList<Integer>(); //no fixed size mentioned
listOfInt .add(1);
listOfInt .add(2);
listOfInt .add(3);
//now convert it to array 
Integer[] arrayOfInt = list.toArray(new Integer[listOfInt .size()]);

回答by tom

Your title is confusing. Are you using an ArrayList or an Array.
An ArrayListexpands and shrinks as needed each time you call the add, removemethod respectively (or any other add/remove variant). There is no need to manage its size yourself.

你的标题令人困惑。您使用的是 ArrayList 还是 Array。
ArrayList膨胀和收缩,因为每个调用所需的时间addremove分别法(或任何其它添加/删除变体)。没有必要自己管理它的大小。

A list is initialized as follows:

一个列表初始化如下:

List<Integer> lst = new ArrayList<Integer>();

Now you have a list where you can add a virtual infinite amount of elements.

现在您有一个列表,您可以在其中添加虚拟无限数量的元素。

An arrayneeds its size on initialization which cannot be changed without reinitializing.

Anarray在初始化时需要它的大小,如果不重新初始化就无法更改。