Reputation: 12205
I'm getting an error when I try to create an array of byte arrays in groovy. My code is:
def patch0 = [0, 2, 4, 8, 16] as byte[];
def patch1 = [0, 3, 6, 12, 24] as byte[];
def patches = [patch0, patch1] as byte[];
The error I'm getting is:
GroovyCastException: Cannot cast object '[B@7630e551' with class '[B' to class 'java.lang.Number'
Upvotes: 2
Views: 1642
Reputation: 392
I think your problem is that when you cast the array to a byte[] in the third line, Groovy is trying to cast each array to a byte. If you change that cast to a two-dimensional byte array the error goes away.
def patch0 = [0, 2, 4, 8, 16] as byte[]
def patch1 = [0, 3, 6, 12, 24] as byte[]
def patches = [patch0, patch1] as byte[][]
Upvotes: 5
Reputation: 13859
Problem is, that [patch0, patch1]
is an array of byte[]
arrays. It's not an array concatenation. Its [[0, 2, 4, 8, 16], [0, 3, 6, 12, 24]]
which cannot be cast to byte[]
You could use flatten()
method like
def p = [patch0, patch1].flatten() as byte[]
Or do smth like
((patch0 as List) + (patch1 as List) ) as byte[]
Or you can ommit a cast
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.
Versions above is Groovyer, but may be not as optimal.
Maybe faster solution will be smth from, How can I concatenate two arrays in Java? but most of all solutions there are verbose, Java-way, or use external libraries like ApacheCommon
Or look a t specific byte array Java concatenation. Easy way to concatenate two byte arrays
Upvotes: 2