0

I have a function taking an int array and need to have that array put into an arraylist

So I use list.addAll(Arrays.asList(array));

However since list is ArrayList<Integer>, the addAll only accepts Integer[] instead of int[]

How should I box the primitive array into an Integer Object array?

4

4 回答 4

3

You can use ArrayUtils from Apache Commons:

Integer[] integerArray = ArrayUtils.toObject(intArray);

to follow on from this, to create a List<Integer>, you can use:

List<Integer> integerList = Arrays.asList(ArrayUtils.toObject(intArray));
于 2012-08-26T00:47:02.153 回答
2
static void addAll(final Collection<Integer> collection, final int[] v) {
  for (final int i : v) {
    collection.add(i);
  }
}
...
addAll(list, array);
于 2012-08-26T00:46:29.000 回答
1

Iterate through the int array and instantiate new Integer objects, and place them in the ArrayList. You won't be able to use autoboxing since that only works for primitives. Arrays aren't primitive types.

于 2012-08-26T00:40:24.080 回答
0

If you have Guava, you can just use

list.addAll(Ints.asList(array));

...which, by the way, creates fewer unnecessary objects than the Apache Commons technique will. (Specifically, it won't bother creating an Integer[]; it'll just return a List<Integer> view of an int[].)

Disclosure: I contribute to Guava.

于 2012-08-26T02:40:59.420 回答