在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;
}
Run Code Online (Sandbox Code Playgroud)
首先,如果你的代码必然会失败a.length + b.length > 100.你应该使用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];
Run Code Online (Sandbox Code Playgroud)
对此:
c[i] = b[i - a.length];
Run Code Online (Sandbox Code Playgroud)
......或者根据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;
}
Run Code Online (Sandbox Code Playgroud)
更简单:)
| 归档时间: |
|
| 查看次数: |
128 次 |
| 最近记录: |