Comparison operators on
Array
s do not compare their contents or values30 def readFile(path: String): String = Source.fromFile(path).mkString
31
32 @Deprecated()
33 def cmpArray1(arr1: Array[Int], arr2: Array[Int]): Boolean = arr1 == arr234 def stringifyArray(arr: Array[Int]): String = arr.toString
35}
36
Description
Using the conventional comparison operators such as ==
or !=
do not necessarily compare the contents of arrays. Rather, the said operators check if the entities on both sides refer to the same object or not. To put it in simpler terms, they check reference, not contents. To compare the contents of 2 Array
s, use sameElements
.
Bad practice
val a = Array(1, 2)
val b = Array(1, 2)
val c = a
a == b // false!
a == c // true, because they both refer to same obj, i.e. `Array(1, 2)`
Recommended
val a = Array(1, 2)
val b = Array(1, 2)
a.sameElements(b) // true