3

I am newbie in android. I want to resize a byte array in function. Is it possible or not. If any problem please suggest a solution to do it.

public void myfunction(){
    byte[] bytes = new byte[1024];
    ....................
    .... do some operations........
    ................................
    byte[] bytes = new byte[2024];
}
Riskhan
  • 4,434
  • 12
  • 50
  • 76

5 Answers5

8

To achieve the effect of resizing a byte array without loosing the content, there are several solutions in Java already mentioned:

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

2) System.arraycopy() (see the answers of jimpic, kgiannakakis, and UVM)

Something like:

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) I would like to add a third way which I think is most elegant: 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

Of course there are further solutions (e.g. copying the bytes in a loop). Concerning efficiency, see this

Community
  • 1
  • 1
Hartmut Pfitzinger
  • 2,304
  • 3
  • 28
  • 48
4

You can't resize an array in Java. You could use a List to do what you want:

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

Another way will be to use System.arraycopy. In that case you will create a second array and copy the content of the first array into it.

Hartmut Pfitzinger
  • 2,304
  • 3
  • 28
  • 48
kgiannakakis
  • 103,016
  • 27
  • 158
  • 194
2

You cannot do that. But you can create a new array and use System.arraycopy to copy the old contents to the new one.

jimpic
  • 5,360
  • 2
  • 28
  • 37
2

You can do it like this:

bytes = new byte[2024];

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

Ashley Medway
  • 7,151
  • 7
  • 49
  • 71
UVM
  • 9,776
  • 6
  • 41
  • 66
1

Use ArrayList<Byte> instead, Java arrays don't allow resizing, ArrayLists do, but make it a little bit different. You can't specify their size (actually you needn't - it is done automatically), you may specify initial capacity (which is good practice if you know how many elements will the ArrayList contain):

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'd recommend you to look through this Java Collections tutorial.

a.ch.
  • 8,285
  • 5
  • 40
  • 53