I am declaring a byte array which is of unknown size to me as it keeps on updating, so how can I declare the byte array of infinite size/variable size?
Creating a Dynamic Array in JavaArrayList<data-type> arr=new ArrayList<>(); Using this, we can create an ArrayList of that specific data type whose initial capacity is 10. Explanation: We have created a dynamic array i.e., an ArrayList of integers arr and then checked its size.
The 32-bit Java int can go to a maximum of 2,147,483,647, so that is the theoretical maximum Java array size.
ByteArrayOutputStream will allow for writing to a dynamic byte array. However, methods such as remove, replace and insert are not available. One has to extract the byte array and then manipulate it directly.
You cannot declare an array of infinite size, as that would require infinite memory. Additionally, all the allocation calls deal with numbers, not infinite quantities.
You can allocate a byte buffer that resizes on demand. I believe the easiest choice would be a ByteArrayOutputStream
.
ByteBuffer
has an API which makes manipulation of the buffer easier, but you would have to build the resize functionality yourself. The easiest way will be to allocate a new, larger array, copy the old contents in, and swap the new buffer for the old.
Other answers have mentioned using a List<Byte>
of some sort. It is worth noting that if you create a bunch of new Byte()
objects, you can dramatically increase memory consumption. Byte.valueOf
sidesteps this problem, but you have to ensure that it is consistently used throughout your code. If you intend to use this list in many places, I might consider writing a simple List
decorator which interns all the elements. For example:
public class InterningList extends AbstractList<Byte>
{
...
@Override
public boolean add(Byte b) {
return super.add(Byte.valueOf(b));
}
...
}
This is not a complete (or even tested) example, just something to start with...
Arrays in Java are not dynamic. You can use list instead.
List<Byte> list = new ArrayList<Byte>();
Due to autoboxing feature you can freely add either Byte objects or primitive bytes to this list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With