简体   繁体   English

比较Groovy中的字节数组

[英]comparing byte arrays in groovy

I'm declaring byte arrays in Groovy: 我在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. 如何根据数组的每个元素是否相同,比较两个数组以返回true / false。

I tried this in groovysh but it keeps erroring out: 我在groovysh尝试过此方法,但始终groovysh

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. 首先,似乎您正在通过groovysh使用groovy shell。对于groovysh,声明变量时必须省略'def'-这是外壳的怪癖。

You are getting this error because after executing def array1 = [-1,5,3] as byte[] , array1 is undefined. 之所以会出现此错误,是因为在将def array1 = [-1,5,3] as byte[] ,未定义array1。

Second, the equals() method won't behave the way that you expect in this situation - you will need to use the '==' operator instead. 其次,在这种情况下,equals()方法将无法达到预期的效果-您将需要使用'=='运算符。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM