You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中ByteBuffer转int数组抛出UnsupportedOperationException问题

为什么ByteBuffer的asIntBuffer()返回的IntBuffer调用array()会抛出UnsupportedOperationException?

核心原因

  • ByteBuffer.allocate()创建的是非直接字节缓冲区,它底层维护了独立的byte[]数组,所以byteBuffer.array()能直接返回这个数组。
  • byteBuffer.asIntBuffer()返回的是视图缓冲区:它没有自己的int[]底层存储,只是把原ByteBuffer的字节数组按int的字节结构(默认大端序)做了一层映射,用来以int为单位读写数据。这种视图缓冲区不支持array()方法——因为不存在可暴露的int[]数组,调用自然会抛出UnsupportedOperationException。

解决方法

如果需要得到对应的int[]数组,可以用以下两种方式:

方式1:从IntBuffer中读取到新创建的int数组

int[] intArray = new int[]{1, 2};
ByteBuffer byteBuffer = ByteBuffer.allocate(intArray.length * 4);
IntBuffer ib = byteBuffer.asIntBuffer();
ib.put(intArray);

// 切换到读模式(put操作后缓冲区位置在末尾,需要重置到起始位置)
ib.flip();
int[] result = new int[ib.capacity()];
ib.get(result);
System.out.println(Arrays.toString(result)); // 输出 [1, 2]

方式2:从原ByteBuffer的字节数组手动转换为int数组

int[] intArray = new int[]{1, 2};
ByteBuffer byteBuffer = ByteBuffer.allocate(intArray.length * 4);
IntBuffer ib = byteBuffer.asIntBuffer();
ib.put(intArray);

byte[] byteArray = byteBuffer.array();
int[] result = new int[byteArray.length / 4];
for (int i = 0; i < result.length; i++) {
    // 按大端序解析每4个字节为int
    result[i] = ((byteArray[i*4] & 0xFF) << 24) 
              | ((byteArray[i*4+1] & 0xFF) << 16) 
              | ((byteArray[i*4+2] & 0xFF) << 8) 
              | (byteArray[i*4+3] & 0xFF);
}
System.out.println(Arrays.toString(result)); // 输出 [1, 2]

内容的提问来源于stack exchange,提问作者Seb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 11:20:28