2

I need to do lots of conversions between primitivetype[] and boxedtype[] (both directions).
Such as: Integer[] <-> int[], Double[] <-> double[], ...

I wanted to know, if there's some quasi-standards APIs out there, which provide such functionality, before I write such utility methods by myself.

Java has 8 primitive types, so it would be quite a (copy-paste) work...

Thank you.

java.is.for.desktop
  • 9,703
  • 10
  • 62
  • 100
  • Why are you using primitive arrays instead of lists? Just curious – OscarRyz Feb 12 '10 at 20:03
  • Primitive arrays are lots faster and more memory-efficient (think of operations on huge number matrices) ;) But to be able to generalize certain functionality, I also need boxed arrays. – java.is.for.desktop Feb 12 '10 at 20:09
  • I see. Probably using an initial size in the List big enough would make it as fast and efficient as bare arrays. After all, `ArrayList` for instance uses arrays as underlaying store. – OscarRyz Feb 12 '10 at 20:15
  • Yes, it would be probably similarly fast, but not as memory efficient: boxed types are objects, each one of them has an overhead (compared to primitive types). Also, think of garbage collection: what is faster, freeing a fixed primitive array, or millions of objects? *(I would guess, it's quite a difference).* – java.is.for.desktop Feb 12 '10 at 20:28
  • Related: http://stackoverflow.com/questions/718554/how-to-convert-an-arraylist-containing-integers-to-primitive-int-array, http://stackoverflow.com/questions/1073919/how-to-convert-int-into-listinteger-in-java, http://stackoverflow.com/questions/880581/java-convert-int-to-integer, http://stackoverflow.com/questions/960431/how-to-convert-listinteger-to-int-in-java, – finnw Feb 13 '10 at 01:12
  • **Related? Yes. Close because of duplicate? No.** I asked specifically for an API, which "automates" the conversion process. Those questions (and their answers) address more a possible self-made implementation. – java.is.for.desktop Feb 13 '10 at 07:38

2 Answers2

3

ArrayUtils

ArrayUtils.toObject( primitive[] )

and

ArrayUtil.toPrimitive( wrapper[] )

OscarRyz
  • 184,433
  • 106
  • 369
  • 548
Matthew Flaschen
  • 255,933
  • 45
  • 489
  • 528
0

Lately I've written a LGPL3 library, so it isn't stardard nor widely adopted, that try to addressing these problems:

Integer[] boxed = ... ;
int[] primitive = $(boxed).toIntArray();

and viceversa:

boxed = $(boxed).toArray();

But I'm hoping that you will appreciate some extra features like casting:

byte[] bytes = ...;
int[] ints = $(bytes).toIntArray();
short[] shorts = $(bytes).toShortArray();
dfa
  • 107,531
  • 29
  • 184
  • 223