patternjavaMinor
Use a Java Array like a List
Viewed 0 times
arraylikejavalistuse
Problem
I'm saving string values in an array one at a time so I cannot initialize the array with the values all at once. After I'm done with the array I need to pass it to another class that is expected a
Normally I would use a
String array.Normally I would use a
List but the end result is expecting an Array so I stuck with the Array. I'm having second thoughts though because maybe it would have better performance if I used a List then when I'm finished filling up the List I could use List.toArray and get the Array that way? Here is majority of the Array code I wrote that takes one argument at a time and adds it to the Array,public String[] addArgument(String[] arguments, String arg) {
String[] temp = new String[arguments.length + 1];
for(int i=0; i<arguments.length; i++)
temp[i] = arguments[i];
temp[arguments.length] = arg;
arguments = temp;
temp = null;
return arguments;
}Solution
You should use the
Note that the array need not be the same size, there are two cases to consider:
List#toArray method, you want to use the generic method, so not the one returning Object[], for this to work you need to supply an array of the correct size, such that it can store the data there.List list = ...;
String[] = list.toArray(new String[list.size()]);Note that the array need not be the same size, there are two cases to consider:
- If `array.length
- Else, it will put the data in the input array.
Code Snippets
List<String> list = ...;
String[] = list.toArray(new String[list.size()]);Context
StackExchange Code Review Q#57703, answer score: 8
Revisions (0)
No revisions yet.