Reputation: 923
I have an array name "asset" with 4 number. I then converted it to be stored in arraylist. Then with the arraylist copy to another array. Is this algorithm correct? After adding 5 the array should be able to show 5 number now
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);
Upvotes: 0
Views: 146
Reputation: 45080
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.
Upvotes: 2
Reputation: 11483
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.
Upvotes: 0