27

the biggest problem on java arrays , they require copying to edit. I am using AMD Aparapi , which i get byte array from my calculations. I need to show that byte array as a bytebuffer "without copying"

byte aparapiData[];
ByteBuffer buffer;
...
//here bytebuffer
buffer.clear();
buffer.put(aparapiData);
buffer.flip();

socket.write(buffer);

The problem here on code , buffer.put is copying byte array to bytebuffer. And also there is reverse problem to convert byte array to bytebuffer.

Are they really require copying data? I can send pure data on C++ without copying.

How can i solve this issue on Java ?

3
  • 1
    Why not socket.write(aparapiData)?
    – user253751
    Jun 26, 2015 at 0:54
  • 1
    byte aparapiData[] should really be byte[] aparapiData; the fact that it's an array is part of the data type, not the name.
    – Sam Estep
    Jun 26, 2015 at 0:55
  • 1
    Java arrays do not 'require copying to edit'. And nobody is forcing you to use NIO channels. What's your actual problem?
    – user207421
    Jun 26, 2015 at 4:32

1 Answer 1

51

To get a ByteBuffer that points to an existing byte array, you can use the wrap function:

byte[] array = /* something */;
ByteBuffer buffer = ByteBuffer.wrap(array);

To get a byte array that points to an existing ByteBuffer, you can use the array method:

ByteBuffer buffer = /* something */;
byte[] array = buffer.array();

However, note that the latter only works when the ByteBuffer is backed by an array (i.e. if hasArray returns true).

The reason for this lack of symmetry is that a ByteBuffer could be implemented in any number of different ways. Sometimes it is implemented as just an array in memory, but it's quite possible that it could read data from the disk or from the network or from some other source when queried. In this case, you can't just access the underlying array because there is none.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.