2

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

Kraiden
  • 567
  • 3
  • 18

2 Answers2

2

There are ready to use methods java.util.Arrays.asList and com.google.common.primitives.Ints.asList.

kan
  • 28,279
  • 7
  • 71
  • 101
  • 1
    `Arrays.asList` returns a `List`, not an `ArrayList`. Also, even if `List list = Arrays.asList(1, 2, 3);` compiles, `List list = Arrays.asList(new int[]{1, 2, 3});` doesn't compile. With an array argument, the compiler will think that the return type is a `List`. – rgettman Mar 20 '13 at 00:09
  • @rgettman is right. Only Guava's `Ints.asList` would work correctly. See my answer [here](http://stackoverflow.com/questions/10676185/what-is-wrong-here-i-get-a-java-lang-classcastexception-error-but-i-cant-see-w/10676223#10676223) for example. – Paul Bellora Mar 20 '13 at 00:45
2

There's no generic method that can work with primitives, because primitives can't be a generic type. The closest you could come in pure Java is to overload getArrayList with an int[]...

public static ArrayList<Integer> getArrayList(int[] a){
    ArrayList<Integer> retList = new ArrayList<Integer>();
    for (int i : a){ 
        retList.add(i); 
    }
    return retList;
}

which will box your int for you. It's not generic, and you'd need a new overload for each primitive array type, but that's the closest solution I can think of.

rgettman
  • 176,041
  • 30
  • 275
  • 357