在Android中调整字节数组大小

3

我是一个 Android 新手。我想在一个函数中调整一个字节数组的大小,是否可能?如果有任何问题,请建议一种解决方案。

public void myfunction(){
    byte[] bytes = new byte[1024];
    ....................
    .... do some operations........
    ................................
    byte[] bytes = new byte[2024];
}
5个回答

8
为了达到调整字节数组大小并保留其中内容的效果,在Java中已经有几种解决方案,包括:
1) ArrayList(请参考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

当然还有其他解决方案(例如循环复制字节)。关于效率问题,请参阅此页面


4

在Java中无法调整数组大小。你可以使用一个列表来实现你想要的功能:

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

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


2

你不能这样做。但是你可以创建一个新的数组,并使用System.arraycopy将旧内容复制到新数组中。


2
你可以这样做:
bytes = new byte[2024];

但是您的旧内容将会被丢弃。如果您需要保留旧数据,那么需要创建一个新的字节数组,并使用System.arrayCopy() 方法将数据从旧数组复制到新数组中。


1

使用 ArrayList<Byte> 替代 Java 数组,因为 Java 数组不允许调整大小,而 ArrayList 可以。但是需要注意一点,ArrayList 不能指定其大小(实际上也不需要 - 它会自动完成),但可以指定初始容量(如果您知道 ArrayList 将包含多少元素,则这是一个好的做法):

byte myByte = 0;
ArrayList<Byte> bytes = new ArrayList<Byte>(); //size is 0
ArrayList<Byte> bytes2 = new ArrayList<Byte>(1024); //initial capacity specified
bytes.add(myByte); //size is 1
...

我建议您浏览一下这个Java集合教程

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接