当我尝试在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 '[B@7630e551' with class '[B' to class 'java.lang.Number'
答案 0 :(得分:5)
我认为你的问题是当你将数组转换为第三行的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[][]
答案 1 :(得分:2)
问题是,[patch0, patch1]
是byte[]
数组的数组。它不是数组连接。其[[0, 2, 4, 8, 16], [0, 3, 6, 12, 24]]
无法转换为byte[]
您可以使用{/ 1}}方法,例如
flatten()
或者像
那样做def p = [patch0, patch1].flatten() as byte[]
或者你可以省略演员
((patch0 as List) + (patch1 as List) ) as byte[]
上面的版本是Groovyer,但可能不是最佳版本。
也许更快的解决方案将来自How can I concatenate two arrays in Java?,但大多数解决方案都是冗长的,Java方式或使用外部库,如 ApacheCommon
或者查看特定的字节数组Java连接。 Easy way to concatenate two byte arrays