0

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);
8
  • 1
    Define correct. What's your actual goal, here? Get a copy of an array? Translate between arrays and ArrayList for an assignment? Commented Sep 27, 2013 at 6:56
  • 1
    you can probably do some type safety like List<String> but anyways I am not trying to get why are you coping to a list and copy them back.... had it been a Set I would have understood Commented Sep 27, 2013 at 6:57
  • it meets my requirements Commented Sep 27, 2013 at 6:57
  • not assignment but I just want to know if this way of doing is right Commented Sep 27, 2013 at 6:57
  • Why are you using array at all, if the number of elements are varying? Commented Sep 27, 2013 at 6:58

3 Answers 3

2

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.
1

Use just Arrays.asList(asset);

0

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.

2
  • how about having first 4 number to be fixed and the rest being dynamically added Commented Sep 27, 2013 at 7:01
  • If you mean having the first 4 values unchangeable, then why would you have them in a collection if you know what they are? What purpose would that be serving? Commented Sep 27, 2013 at 7:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.