Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an array of int:

int[] a = {1, 2, 3};

I need a typed set from it:

Set<Integer> s;

If I do the following:

s = new HashSet(Arrays.asList(a));

it, of course, thinks I mean:

List<int[]>

whereas I meant:

List<Integer>

This is because int is a primitive. If I had used String, all would work:

Set<String> s = new HashSet<String>(
    Arrays.asList(new String[] { "1", "2", "3" }));

How to easily, correctly and succinctly go from:

A) int[] a...

to

B) Integer[] a ...

Thanks!

share|improve this question
1  
Possible duplicate of: stackoverflow.com/questions/1073919/… –  David B Aug 19 '12 at 23:09

3 Answers 3

up vote 5 down vote accepted

Some further explanation. The asList method has this signature

public static <T> List<T> asList(T... a)

So if you do this:

List<Integer> list = Arrays.asList(1, 2, 3, 4)

or this:

List<Integer> list = Arrays.asList(new Integer[] { 1, 2, 3, 4 })

In these cases, I believe java is able to infer that you want a List back, so it fills in the type parameter, which means it expects Integer parameters to the method call. Since it's able to autobox the values from int to Integer, it's fine.

However, this will not work

List<Integer> list = Arrays.asList(new int[] { 1, 2, 3, 4} )

because primitive to wrapper coercion (ie. int[] to Integer[]) is not built into the language (not sure why they didn't do this, but they didn't).

As a result, each primitive type would have to be handled as it's own overloaded method, which is what the commons package does. ie.

public static List<Integer> asList(int i...);
share|improve this answer

You can use ArrayUtils in Apache Commons:

int[] intArray  = { 1, 2, 3 };
Integer[] integerArray = ArrayUtils.toObject(intArray);
share|improve this answer
    
If Commons has a method to do this, it means there wasn't a way to do it with the base JDK... thanks for the pointer! –  Robottinosino Aug 19 '12 at 23:28

Or you could easly use Guava to convert int[] to List<Integer>:

Ints.asList(int...)

asList

public static List<Integer> asList(int... backingArray)

Returns a fixed-size list backed by the specified array, similar to Arrays.asList(Object[]). The list supports List.set(int, Object), but any attempt to set a value to null will result in a NullPointerException.

The returned list maintains the values, but not the identities, of Integer objects written to or read from it. For example, whether list.get(0) == list.get(0) is true for the returned list is unspecified.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.