java byte[] 中的数组索引超出范围

ArrayIndex out of bound in java byte[]

谁能解决这个问题

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);
   }
}

临时文件的长度是 5 并且您正在尝试复制到 length 16 的散列,这会抛出异常。

System.arraycopy(source, sourcePosition, destination, destinationPosition, length);

Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dest. The number of components copied is equal to the length argument.

您的源数组必须有 16 个组件才能复制,但这里的长度为 5,而您正试图从 temp 复制 16 个组件。 您可以增加 temp 数组(即 byte[] temp = "smile is the most important thing.".getBytes();)。

根据 System.arraycopy 上的 javadoc: 如果以下任一情况为真,则抛出 IndexOutOfBoundsException 并且不修改目标:

  • srcPos 参数为负。
  • destPos 参数为负。
  • 长度参数为负。
  • srcPos+length 大于src.length,源数组的长度。
  • destPos+length 大于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