我是android的新手.我想在函数中调整字节数组的大小.有可能吗?如有任何问题,请提出解决方案.
public void myfunction(){
byte[] bytes = new byte[1024];
....................
.... do some operations........
................................
byte[] bytes = new byte[2024];
}
Run Code Online (Sandbox Code Playgroud)
为了在不丢失内容的情况下实现调整字节数组大小的效果,已经提到了几种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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
当然还有其他解决方案(例如,在循环中复制字节).关于效率,请看这个
| 归档时间: |
|
| 查看次数: |
11486 次 |
| 最近记录: |