How to extend the allocated memory of a bytebuffer
bytebuffer, java
Solution
You can't. This is by design. You can allocate a new byte buffer and write the overflowing data to that. You can keep the ByteBuffers in a LinkedList (which will grow as needed), and you can even spool off the old ones to disk, if you're running out of memory to allocate new ones. If each ByteBuffer is the same size, trivial equations will let you access it as if it where just the one buffer, but you lose the ability to use slicing or compacting, or any of the cool things you can do with one of those. :)
But like people have said over and over again, it depends on what you need it for.
Problem
I have a bytebuffer and I put Ints,Chars etc.. Because I do not know how much space I need I would like to dynamically growth the bytebuffer. How can this be done ? Example : - I have a Bytebuffer of 2 bytes - I add a character to the bytebuffer (bytebuffer is full now ) - I like to add a Integer to the bytebuffer by extending the bytebuffer with 4 bytes. I can't allocate my bytebuffer with 6 bytes at start. ``` ByteBuffer byteBuffer = ByteBuffer.allocate(2); byteBuffer.putChar('a'); byteBuffer.putInt(1); ``` I am very impressed, on how many people are working on my question that is some minutes old. Thank you all very much and thanks also to Stackoverflow, which is a great Plattform ! All of you asked, what I am doing. So I try to explain it here. My usecase: I have structured data represented as javaobjects (javaclasses) which I would like to store and read to/from a db. Reading should be very fast. What I have done so far: java serialized and deserialized and stored it in a blob -> works well but too slow. tried several 3rd party serializer like kryo (which is very good), but not useable in my case (android). my new strategy :-) : I do my own externalizing of my class. for that I would like to construct my entire data of my class sequential as an array of bytes. This can be slow. Then I store the bytearray to a blob in my db. When reading I would like to read the bytearray at once (bytearray is about 10k). (I will have a lot of them). Then parsing the bytearray to extract the structured data. I thought using a bytebuffer is ideal for doing this, because of methods like putX and readX ? (X for chars, floats, int)