I'm declaring byte arrays in Groovy:
def array1 = [-1,5,3] as byte []
def array2 = [-5,2,9] as byte []
How can I compare the two arrays to return true/false based on whether each element of the array is same.
I tried this in groovysh
but it keeps erroring out:
groovy:000> def array1 = [-1,5,3] as byte[]
===> [B@18e501c
groovy:000> def array2 = [-5,2,9] as byte[]
===> [B@5e860ba9
groovy:000> array1.equals array2
ERROR groovy.lang.MissingPropertyException:
No such property: array1 for class: groovysh_evaluate
at groovysh_evaluate.run (groovysh_evaluate:2)
...
There are a couple of issues here.
First, it appears that you are using the groovy shell, via 'groovysh' With groovysh, you have to omit the 'def' when declaring a variable - it's a quirk of the shell.
You are getting this error because after executing def array1 = [-1,5,3] as byte[]
, array1 is undefined.
Second, the equals() method won't behave the way that you expect in this situation - you will need to use the '==' operator instead.
Here's what I get:
groovy:000> array1 = [-1,5,3] as byte[]
===> [B@1d429498
groovy:000> array2 = [-5,2,9] as byte[]
===> [B@ac1b161
groovy:000> array3 = [-1,5,3] as byte[]
===> [B@5ca3ce3f
groovy:000> array1.equals array2
===> false
groovy:000> array1.equals array3
===> false
groovy:000> array1 == array2
===> false
groovy:000> array1 == array3
===> true
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.