Robottinosino Robottinosino - 4 years ago 285
Java Question

Java int[] array to HashSet<Integer>

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:


whereas I meant:


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...


B) Integer[] a ...


Answer Source

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...);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download