0

Say I have a List<Integer> ls and I know its length could we allocate length*4 bytes for bytebuffer and use put to directlty read ls into the buffer?

user3495562
  • 335
  • 1
  • 4
  • 16

1 Answers1

1

This should do what you're looking for:

ByteBuffer buffer = ByteBuffer.allocate(ls.size()*4);
for (Integer i: ls)
    buffer.putInt(i);

One caveat: This function assumes that your list does not contain any null-entries.

I don't think you can do much better than this, since the underlying array of Integer objects in ls is an array of references (pointers) to these Integer objects rather than their contained int-values. The actual Integer objects will reside in memory in some random order, dictated roughly by when they were created. So, it's unlikely that you would find some consecutive block of memory that contains the data that you would need to copy into your ByteBuffer (I think this is what you meant by "directly reading" it.). So, something like using sun.misc.Unsafe will probably not be able to help you here.

Even if you had an int[] instead of a List<Integers> you probably won't be able to reliably read the data directly from memory into your ByteBuffer, since some JVM's on 64-bit machines will align all values on 64-bit address-locations for faster access, which would lead to "gaps" between your ints. And then there is the issue of endianness, which might differ from platform to platform...

Edit:

Hmmm... I just took a look at the OpenJDK source-code for the putInt()-function that this would be calling... It's a horrendous mess of sub-function-calls. If the "sun"-implementation is as "bad", you might be better off to just do the conversion yourself (using shifting and binary-ops) if you're looking for performance... The fastest might be to convert your Integers into a byte[] and then using ByteBuffer.wrap(...) if you need the answer as a ByteBuffer. Let me know if you need code...

Markus A.
  • 12,349
  • 8
  • 52
  • 116
  • Thanks, I have used a similar method. That is what I am confusing that could I just put the List as a whole into it. Now I realize we could not. – user3495562 Apr 13 '14 at 03:03