问题
val a: Array[Int] = Array(1,2,4,5)
val b: Array[Int] = Array(1,2,4,5)
a==b // false
Is there a pattern-matching way to see if two arrays (or sequences) are equivalent?
回答1:
You need to change your last line to
a.deep == b.deep
to do a deep comparison of the arrays.
回答2:
From Programming Scala:
Array(1,2,4,5).sameElements(Array(1,2,4,5))
回答3:
a.corresponds(b){_ == _}
Scaladoc:
trueif both sequences have the same length andp(x, y)istruefor all corresponding elementsxofthiswrapped array andyofthat, otherwisefalse
回答4:
For best performance you should use:
java.util.Arrays.equals(a, b)
This is very fast and does not require extra object allocation. Array[T] in scala is the same as Object[] in java. Same story for primitive values like Int which is java int.
来源:https://stackoverflow.com/questions/5393243/how-do-i-compare-two-arrays-in-scala