2015-05-09 55 views
-2

任何機構都可以解決這個問題。ArrayIndex在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); 
    } 
} 
+1

你試過打印'temp'數組的長度?另請參閱stacktrace,瞭解產生線路錯誤的原因。 – ersnh

回答

1

長度溫度是5,你要複製到哈希length16被拋出異常。

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

複製從指定的源陣列的陣列,開始指定位置到目的地 陣列的指定位置。將數組組件的子序列從src引用的源數組012h複製到dest引用的目標數組。 複製的組件的數量等於長度參數

您的源陣列必須有16個要複製的組件,但此處長度爲5,並且您試圖從temp複製16個組件。 您可以增加temp陣列(即byte[] temp = "smile is the most important thing.".getBytes();)。

2

作爲每javadoc的上System.arraycopy: 如果下列任何一項爲真,拋出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