Is there a better way of achieving this?
public static List toList(String[] array) {
List list = new ArrayList(array.length);
What do you mean by better way:
more readable:
List list = new ArrayList(Arrays.asList(array));
less memory consumption, and maybe faster (but definitely not thread safe):
public static List toList(String[] array) {
if (array==null) {
return new ArrayList(0);
} else {
int size = array.length;
List 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.