I have a method to convert an array to an ArrayList as follows:
public static <T> ArrayList<T> getArrayList(T[] a){
ArrayList<T> retList = new ArrayList<T>();
for (T i : a){
retList.add(i);
}
return retList;
}
which works fine for object arrays such as:
String[] arr = {"String","'nother string","etc"};
ArrayList<String> stringList = initArrayList(arr);
But not with primitive arrays:
int[] arr2 = {1,2,3};
ArrayList<Integer> intList = initArrayList(arr2); //Compiler is insulted by this.
I guess I have to convert the array to an Integer array if I want the method to work, but is there a way to make the method a little smarter about how it handle's this?
The Java tutorials site has the following:
static <T> void fromArrayToCollection(T[] a, Collection<T> c) {
for (T o : a) {
c.add(o); // Correct
}
}
Which would work, but I'd like the method to be creating the ArrayList.
Also, this is just for my own amusement, so the type of Collection doesn't really matter, I just used ArrayList when I wrote the method.
Thanks