2014-01-10 101 views
2

當我嘗試在groovy中創建一個字節數組數組時,出現錯誤。我的代碼是:無法在groovy中創建一個字節數組數組

def patch0 = [0, 2, 4, 8, 16] as byte[]; 
def patch1 = [0, 3, 6, 12, 24] as byte[]; 

def patches = [patch0, patch1] as byte[]; 

我得到的錯誤是:

GroovyCastException: Cannot cast object '[[email protected]' with class '[B' to class 'java.lang.Number' 

回答

4

我覺得你的問題是,當你施放數組中的第三行一個byte [],Groovy的嘗試將每個數組轉換爲一個字節。如果將該轉換更改爲二維字節數組,則錯誤消失。

def patch0 = [0, 2, 4, 8, 16] as byte[] 
def patch1 = [0, 3, 6, 12, 24] as byte[] 

def patches = [patch0, patch1] as byte[][] 
2

問題是,[patch0, patch1]陣列byte[]陣列。這不是數組連接。它[[0, 2, 4, 8, 16], [0, 3, 6, 12, 24]]不能轉換爲byte[]

你可以使用flatten()方法類似

def p = [patch0, patch1].flatten() as byte[] 

或做水木清華像

((patch0 as List) + (patch1 as List)) as byte[] 

或者你可以ommit鑄造

def patch0 = [0, 2, 4, 8, 16] // will be Collection instance 
def patch1 = [0, 3, 6, 12, 24] 
(patch0 + patch1) as byte[] // You can plus collections, and then cast. 

版本以上是Groovyer,但可能不是 最佳。

也許更快的解決方案將是,How can I concatenate two arrays in Java?不便但最重要的解決方案有冗長,Java的方式,或使用外部庫,例如ApacheCommon

還是看一件T特定字節數組的Java串聯。 Easy way to concatenate two byte arrays