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);
asked Sep 27, 2013 at 6:54
BeyondProgrammer
9232 gold badges15 silver badges32 bronze badges
-
1Define correct. What's your actual goal, here? Get a copy of an array? Translate between arrays and ArrayList for an assignment?James– James2013年09月27日 06:56:14 +00:00Commented Sep 27, 2013 at 6:56
-
1you 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 understoodAurA– AurA2013年09月27日 06:57:07 +00:00Commented Sep 27, 2013 at 6:57
-
it meets my requirementsScary Wombat– Scary Wombat2013年09月27日 06:57:10 +00:00Commented Sep 27, 2013 at 6:57
-
not assignment but I just want to know if this way of doing is rightBeyondProgrammer– BeyondProgrammer2013年09月27日 06:57:16 +00:00Commented Sep 27, 2013 at 6:57
-
Why are you using array at all, if the number of elements are varying?Rohit Jain– Rohit Jain2013年09月27日 06:58:04 +00:00Commented Sep 27, 2013 at 6:58
3 Answers 3
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.
answered Sep 27, 2013 at 7:02
Rahul
45.2k11 gold badges89 silver badges108 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Use just Arrays.asList(asset);
answered Sep 27, 2013 at 6:57
Alex
11.6k7 gold badges39 silver badges52 bronze badges
Comments
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.
answered Sep 27, 2013 at 6:57
Rogue
11.5k6 gold badges51 silver badges74 bronze badges
2 Comments
BeyondProgrammer
how about having first 4 number to be fixed and the rest being dynamically added
Rogue
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?
lang-java