Array to Collection: Optimized code
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.
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.
Arrays.asList(array)
Arrays
uses new ArrayList(array)
. But this is not the java.util.ArrayList
. It's very similar though. Note that this constructor takes the array and places it as the backing array of the list. So it is O(1)
.
In case you already have the list created, Collections.addAll(list, array)
, but that's less efficient.
Update: Thus your Collections.addAll(list, array)
becomes a good option. A wrapper of it is guava's Lists.newArrayList(array)
.
Another way to do it:
Collections.addAll(collectionInstance,array);
What about :
List myList = new ArrayList();
String[] myStringArray = new String[] {"Java", "is", "Cool"};
Collections.addAll(myList, myStringArray);