Java 在android中调整字节数组的大小

Java 在android中调整字节数组的大小,java,android,Java,Android,我是android的新手。我想在函数中调整字节数组的大小。有没有可能。如果有任何问题,请提出解决方案 public void myfunction(){ byte[] bytes = new byte[1024]; .................... .... do some operations........ ................................ byte[] bytes = new byte[2024]; } 使用

我是android的新手。我想在函数中调整字节数组的大小。有没有可能。如果有任何问题,请提出解决方案

public void myfunction(){
    byte[] bytes = new byte[1024];
    ....................
    .... do some operations........
    ................................
    byte[] bytes = new byte[2024];
}
使用
ArrayList
相反,Java数组不允许调整大小,而ArrayList允许调整大小,但会使它有一点不同。您不能指定它们的大小(实际上您不需要-它是自动完成的),您可以指定初始容量(如果您知道
ArrayList
将包含多少个元素,这是一种很好的做法):

byte myByte=0;
ArrayList字节=新的ArrayList()//大小为0
ArrayList bytes2=新的ArrayList(1024)//指定的初始容量
字节。添加(myByte)//大小是1
...

我建议你仔细检查一下。你不能那样做。但是您可以创建一个新数组,并使用System.arraycopy将旧内容复制到新内容。

在Java中无法调整数组的大小。您可以使用a来做您想做的事情:

List<Byte> bytes = new ArrayList<Byte>();
List bytes=new ArrayList();

另一种方法是使用。在这种情况下,您将创建第二个数组,并将第一个数组的内容复制到其中。

您可以这样做:

bytes = new byte[2024];

但是您的旧内容将被丢弃。如果您也需要旧数据,则需要创建一个大小不同的新字节数组,并调用
System.arrayCopy()
方法将数据从旧复制到新。

为了在不丢失内容的情况下实现调整字节数组大小的效果,Java中已经提到了几种解决方案:

1)
ArrayList
(参见a.ch.和Kgianakakis的答案)

2)
System.arraycopy()
(请参阅jimpic、Kgiannakis和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
//
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
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