[英]Dynamic Array List size
How can I set size of a dynamic array with Java? 如何使用Java设置动态数组的大小?
I tried setsize(...)
with the array variable but not working. 我尝试使用数组变量
setsize(...)
但不工作。 How can I do this? 我怎样才能做到这一点?
array size needs to be fixed while initialization, use List
instead and then have array from List
using toArray()
初始化时需要修复数组大小,使用
List
代替,然后使用toArray()
从List
数组
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()]);
Your title is confusing. 你的头衔令人困惑。 Are you using an ArrayList or an Array.
您使用的是ArrayList还是Array。
An ArrayList
expands and shrinks as needed each time you call the add
, remove
method respectively (or any other add/remove variant). 每次调用
add
, remove
方法(或任何其他添加/删除变体)时, ArrayList
根据需要进行扩展和缩小。 There is no need to manage its size yourself. 没有必要自己管理它的大小。
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 array
needs its size on initialization which cannot be changed without reinitializing. array
在初始化时需要其大小,如果不重新初始化则无法更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.