Java中两个连接两个字节数组的简单方法是什么? 我使用了这个函数但出现错误:
java.lang.ArrayIndexOutOfBoundsException: 16
我的职能是:
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;
}
最佳答案
首先,如果 a.length + b.length > 100
,您的代码将绑定(bind)失败。您应该使用 a.length + b.length
作为 c
的长度。
是的,因为当您超过 a.length
时,您仍在尝试使用 b[i]
。假设 a.length 为 50,b.length 为 1。您需要填充 51 个数组元素,但要填充 c[50],您需要 b[0],而不是 b[50]。
所有你需要改变的是:
c[i] = b[i];
对此:
c[i] = b[i - a.length];
... 或者根据 Mureinik 的回答有两个循环。 (我不希望任何一个选项比另一个选项快得多,而且它们绝对是等价的 - 您可以使用您认为最易读的任何一个。)
不过,我建议使用 System.arraycopy
相反:
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;
}
简单多了:)
关于java - 如何在java中连接字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31336282/