简体   繁体   English

Java数组到ArrayList到数组

[英]Java Array to ArrayList to Array

I have an array name "asset" with 4 number. 我有一个带有4个数字的数组名称“ asset”。 I then converted it to be stored in arraylist. 然后,我将其转换为存储在arraylist中。 Then with the arraylist copy to another array. 然后用arraylist复制到另一个数组。 Is this algorithm correct? 这个算法正确吗? After adding 5 the array should be able to show 5 number now 加5后,数组现在应该可以显示5号

List assetList = new ArrayList();
String[] asset = {"1", "2", "3", "4"}; 

Collections.addAll(assetList, asset);

assetList.add("5");

String [] aListToArray = new String[assetList.size()];
aListToArray.toArray(aListToArray);

You need to change this line 您需要更改此行

aListToArray.toArray(aListToArray); // aListToArray to aListToArray itself? This would have given a compilation error

to this 对此

assetList.toArray(aListToArray); // assetList to aListToArray is what you need.

仅使用Arrays.asList(asset);

You can make some simplifications: 您可以进行一些简化:

List assetList = new ArrayList();
String[] asset = {"1", "2", "3", "4"}; 

assetList.addAll(asset);

assetList.add("5");

String [] aListToArray = assetList.toArray(aListToArray);

Overall, the code is correct. 总体而言,该代码是正确的。 However if you want to have a "dynamic array", or a collection of items that changes in size, then don't bother trying to keep something in array form. 但是,如果您想拥有一个“动态数组”或大小可变的项目集合,那么就不必费心尝试将某些内容保持为数组形式。 An arraylist will work fine. 数组列表可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM