简体   繁体   中英

could we read an object directly into the bytebuffer in java?

说我有一个List<Integer> ls ,我知道它的长度可以为字节缓冲区分配length * 4个字节,并使用putltil将ls直接读入缓冲区吗?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM