What is the simple method two concatenate two byte arrays in Java? I used this function but got an error:
java.lang.ArrayIndexOutOfBoundsException: 16
My function is:
public static byte[] concatinate(byte[] a, byte[] b) {
byte[] c = new byte[100];
for (int i = 0; i < (a.length + b.length); i++) {
if (i < a.length) {
c[i] = a[i];
} else {
c[i] = b[i];
}
}
return c;
}
Firstly, your code is bound to fail if a.length + b.length > 100
. You should be using a.length + b.length
as the length of c
.
Yes, because when you've gone past a.length
, you're still trying to use b[i]
. Imagine a.length is 50 and b.length is 1. You've got 51 array elements to populate, but to populate c[50] you need b[0], not b[50].
All you need to change is this:
c[i] = b[i];
To this:
c[i] = b[i - a.length];
... or have two loops instead, as per Mureinik's answer. (I wouldn't expect either option to be significantly faster than the other, and they're definitely equivalent - you can use whichever you find most readable.)
However, I'd recommend using System.arraycopy
instead:
public static byte[] concatenate(byte[] a, byte[] b) {
byte[] c = new byte[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
Much simpler :)
See more on this question at Stackoverflow