Resize byte array in android

I am new to android. I want to resize a byte array in a function. It is possible or not. If there is any problem, please suggest a solution for this.

public void myfunction(){
    byte[] bytes = new byte[1024];
    ....................
    .... do some operations........
    ................................
    byte[] bytes = new byte[2024];
}
+3
source share
5 answers

You can do it as follows:

bytes = new byte[2024];

But your old content will be discarded. If you need old data, then you need to create a new byte array with diff size and call the method System.arrayCopy()to copy the data from the old to the new.

+2
source

To achieve the effect of resizing a byte array without losing content, several solutions have already been mentioned in Java:

1) ArrayList<Byte> (see answers by a.ch. and kgiannakakis)

2) System.arraycopy() (. jimpic, kgiannakakis UVM)

- :

byte[] bytes = new byte[1024];
//
// Do some operations with array bytes
//
byte[] bytes2 = new byte[2024];
System.arraycopy(bytes,0,bytes2,0,bytes.length);
//
// Do some further operations with array bytes2 which contains
// the same first 1024 bytes as array bytes

3) , , , : Arrays.copyOfRange()

byte[] bytes = new byte[1024];
//
// Do some operations with array bytes
//
bytes = Arrays.copyOfRange(bytes,0,2024);
//
// Do some further operations with array bytes whose first 1024 bytes
// didn't change and whose remaining bytes are padded with 0

, (, ). , .

+7

Java. List, , :

List<Byte> bytes = new ArrayList<Byte>();

System.arraycopy. .

+4

. System.arraycopy, .

+2

Use ArrayList<Byte>, instead, Java arrays do not allow resizing, as ArrayLists do, but they do it a little differently. You cannot specify their size (in fact, you do not need to - this is done automatically), you can specify the initial capacity (which is good practice if you know how many elements will contain ArrayList):

byte myByte = 0;
ArrayList<Byte> bytes = new ArrayList<Byte>(); //size is 0
ArrayList<Byte> bytes2 = new ArrayList<Byte>(1024); //initial capacity specified
bytes.add(myByte); //size is 1
...

I would advise you to study this tutorial on Java collections .

+1
source

All Articles