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?

3
  • Loop through the elements of the primitive list, establish an object, and add it to the 2nd list. Commented Aug 26, 2012 at 0:40
  • List<Integer>.addAll accepts neither Integer[] nor int[]. Commented Aug 26, 2012 at 0:42
  • @veer sry I meant asList method :P Commented Aug 28, 2012 at 0:02

4 Answers 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));
Sign up to request clarification or add additional context in comments.

6 Comments

No point in first converting int[] to equivalent Integer[], then wrapping that via Arrays.asList only to copy all when doing list.addAll.
@MichaelBuen I'm afraid I don't quite see your point. I described what list.addAll(Arrays.asList(ArrayUtils.toObject(array))); does. What separate code? If you're stating that Apache Commons is a separate library, yes I'm very well aware of that.
@veer I mean, the integerArray is not involved on second code. They can be used independently. ArrayUtils.toObject need not accept Integer[], it can accept int[] out-of-the-box
@MichaelBuen yes, okay, I am very well aware the snippets are distinct. My point still stands :-p Just figured I'd point out it's doing excessive work. I never stated that ArrayUtils.toObject accepted Integer[]. Maybe you should reread my comment :-)
@veer Well that's Java for us ツ I'm mostly a C# coder, I dabble with Java only recently, it surprises me that a List<int>(works on C#) is not a valid construct even Java already has autoboxing. Cheers! ツ
|
2
static void addAll(final Collection<Integer> collection, final int[] v) {
  for (final int i : v) {
    collection.add(i);
  }
}
...
addAll(list, array);

Comments

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.

Comments

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.

Comments

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.