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

2
  • No, there really isn't. Primitive arrays and generics aren't going to mix. Commented Mar 19, 2013 at 23:53
  • 1
    Have a look at this stackoverflow.com/questions/754294/… Commented Mar 19, 2013 at 23:58

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Had a feeling this might be the case. Kinda sucks, but oh well. Thanks.
+1 and note that you could have it take int... for varargability and initialize capacity by using new ArrayList<Integer>(a.length).
2

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

2 Comments

Arrays.asList returns a List, not an ArrayList. Also, even if List<Integer> list = Arrays.asList(1, 2, 3); compiles, List<Integer> 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<int[]>.
@rgettman is right. Only Guava's Ints.asList would work correctly. See my answer here for example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.