将int []转换为byte []而不创建新对象

pde*_*eva 2 java

我在java中有一个int [],我想转换为byte [].

现在通常的做法是创建一个新的byte [] 4倍大小的int数组,并将所有的int字节逐字节复制到新的字节数组中.

但是,这样做的唯一原因是因为java的类型安全规则.int数组已经是一个字节数组.它只是java不允许将int []转换为byte []然后将其用作byte [].

有没有办法,也许使用jni,使一个int数组看起来像java的字节数组?

Bri*_*new 9

不可以.没有能力使用本机Java阵列接口实现对象.

听起来我想要一个包装int []的对象,并提供以字节数组方式访问它的方法.例如

public class ByteArrayWrapper {
   private int[] array;

   public int getLength() {
      return array.length * 4;
   }

   public byte get(final int index) {
      // index into the array here, find the int, and then the appropriate byte
      // via mod/div/shift type operations....
     int val = array[index / 4];
     return (byte)(val >> (8 * (index % 4)));
   }
}
Run Code Online (Sandbox Code Playgroud)

(以上未经过测试/编译等,取决于您的字节排序要求.这纯粹是说明性的)

  • @pdeva - 如上所述.这就是为什么我的回答开始'不':-)我做了*进一步*突出这个问题后马丁的评论.除了回答'不'之外,我不确定自己有多清楚. (2认同)