java字节[]中的ArrayIndex越界

java字节[]中的ArrayIndex越界,java,bytearray,indexoutofboundsexception,arrays,Java,Bytearray,Indexoutofboundsexception,Arrays,任何机构都能解决这个问题 public class Main { public static void main(String[] args) { byte[] temp = "smile".getBytes(); byte[] hash = new byte[32]; System.arraycopy(temp, 0, hash, 0, 16); System.arraycopy(temp, 0, hash, 15, 16); } } te

任何机构都能解决这个问题

public class Main {
   public static void main(String[] args) {
     byte[] temp = "smile".getBytes();
     byte[] hash = new byte[32];
     System.arraycopy(temp, 0, hash, 0, 16);
     System.arraycopy(temp, 0, hash, 15, 16);
   }
}

temp的长度是
5
,您正试图复制到
length
16
的哈希,这将引发异常

System.arraycopy(source, sourcePosition, destination, destinationPosition, length);
从指定的源数组中复制一个数组,从 指定位置到目的地的指定位置 数组。阵列组件的子序列从源中复制 src引用的数组到dest引用的目标数组。 复制的组件数等于长度参数

源阵列必须有16个组件要复制,但此处的长度为5,您正试图从
temp
复制16个组件。
你可以增加你的
temp
数组(即
byte[]temp=“微笑是最重要的东西。”.getBytes();
)。

根据System.arraycopy上的javadoc: 如果以下任一项为真,则会引发IndexOutOfBoundsException,并且不会修改目标:

  • srcPos参数是否定的
  • destPos参数是否定的
  • 长度参数是负数
  • srcPos+length大于源数组的长度src.length
  • destPos+长度大于dest.length,即目标阵列的长度
PFB代码段:

    byte[] temp = "smile".getBytes();
    byte[] hash = new byte[32];

    System.arraycopy(temp, 0, hash, 0, temp.length);
    // System.arraycopy(temp, 0, hash, 15, 16); // should be used carefully

您是否尝试打印
temp
数组的长度?另请参见产生行错误的stacktrace。