为了达到在不丢失内容的情况下调整字节数组大小的效果,Java中已经提到了几种解决方案:
1) ArrayList<Byte>(见 a.ch. 和 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
当然还有其他解决方案(例如,在循环中复制字节)。关于效率,see this