Is there a better way of achieving this?
public static List<String> toList(String[] array) { List<String> list = new ArrayList(array.length); for(int i=0; i<array.length; i++) list.add(array[i]); return list; }
NOTE: Arrays.asList(a) Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.). I don't want that behavior. I assume that MY function above bypasses that (or am I wrong?)
So, here we have the alternative method:
public static List<String> toList(String[] array) { List<String> list = new ArrayList(array.length); list.addAll(Arrays.asList(array)); return list; }
Just looking at it, I don't believe it's FASTER than the first method.
Step 1: Declare and initialize the array “countryArray”. Step 2: Declare the list object “countryList”. Step 3 : Now, use the method Collections. addAll(Collections,Array).
Arrays due to fast execution consumes more memory and has better performance. Collections, on the other hand, consume less memory but also have low performance as compared to Arrays. Arrays can hold the only the same type of data in its collection i.e only homogeneous data types elements are allowed in case of arrays.
An Array is a collection of similar items. Whereas ArrayList can hold item of different types. An array is faster and that is because ArrayList uses a fixed amount of array.
What do you mean by better way:
more readable:
List<String> list = new ArrayList<String>(Arrays.asList(array));
less memory consumption, and maybe faster (but definitely not thread safe):
public static List<String> toList(String[] array) { if (array==null) { return new ArrayList(0); } else { int size = array.length; List<String> list = new ArrayList(size); for(int i = 0; i < size; i++) { list.add(array[i]); } return list; } }
Btw: here is a bug in your first example:
array.length
will raise a null pointer exception if array is null, so the check if (array!=null)
must be done first.
Arrays.asList(array);
Example:
List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
See Arrays.asList
class documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With