Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Declare a Byte Array of Infinite Size/Dynamic in Java?

Tags:

java

bytearray

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?

like image 960
NewCoder Avatar asked Nov 25 '12 18:11

NewCoder


People also ask

How do you create an array with dynamic size in Java?

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.

What is the maximum size of byte array in Java?

The 32-bit Java int can go to a maximum of 2,147,483,647, so that is the theoretical maximum Java array size.


3 Answers

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.

like image 175
Nathan Avatar answered Oct 11 '22 06:10

Nathan


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

like image 33
Steven Schlansker Avatar answered Oct 11 '22 06:10

Steven Schlansker


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.

like image 36
Juvanis Avatar answered Oct 11 '22 06:10

Juvanis