Java的NIO包中包含了许多缓冲(Buffer)类,使用这些类可以处理所有原始数据类型的数组,用起来和ByteArrayOutputStream一样简单方便。
import java.nio.*;
public class ConcatArrays {
public static void main(String[] args) {
int[] myNumbers=new int[]{1,2,3,4};
int[] yourNumbers=new int[]{5,6,7};
int[] theirNumbers=new int[]{8,9,0};
//按需要分配buffer
IntBuffer intBuffer = IntBuffer.allocate(myNumbers.length+yourNumbers.length+theirNumbers.length);
//放入到buffer
intBuffer.put(myNumbers);
intBuffer.put(yourNumbers);
intBuffer.put(theirNumbers);
//得到合并后的数组
int[] allNumber = intBuffer.array();
//显示合并后的数组
for (int i :allNumber ) {
System.out.print(i);
System.out.print(", ");
}
//各种数据原始类型都有buffer可用,非常方便
LongBuffer longBuffer = LongBuffer.allocate(10);
DoubleBuffer doubleBuffer = DoubleBuffer.allocate(10);
FloatBuffer floatBuffer = FloatBuffer.allocate(10);
ByteBuffer byteBuffer = ByteBuffer.allocate(10);
ShortBuffer shortBuffer = ShortBuffer.allocate(10);
CharBuffer charBuffer = CharBuffer.allocate(10);
}
}