Scala中Seq与Array的==比较行为差异及原因探究
Array and Seq behave differently in equality checks in Scala? Great question! Let's break down why you're seeing this seemingly inconsistent behavior between Array and Seq (and its subtypes like List or Set):
1. Array uses reference equality by default
In Scala, Array is essentially a wrapper around the underlying Java array. When you use the == operator on two Array instances, it's using the default equals method inherited from Object (Java's root class), which checks reference equality—meaning it only returns true if both variables point to the exact same object in memory.
That's why:
Array(1) == Array(1) // returns false
Even though the arrays have the same element, they're two separate objects allocated in different memory locations.
2. Seq (and its subtypes) use structural equality
On the other hand, Seq is a Scala collection trait, and all its standard implementations (like List, Vector, Set) override the equals method to implement structural equality. This means the equality check traverses every element in the collection, comparing each corresponding pair for equality. If all elements match (and for ordered collections like Seq, the order also matches), the method returns true.
Which is why:
Seq(1) == Seq(1) // returns true List(1,2) == List(1,2) // also returns true
How to check content equality for Arrays
If you need to compare the contents of two Arrays instead of their references, you have a couple reliable options:
- Use the
sameElementsmethod for flat arrays:Array(1).sameElements(Array(1)) // returns true - For nested arrays, use
Array.deepEquals:Array(Array(1)).deepEquals(Array(Array(1))) // returns true
内容的提问来源于stack exchange,提问作者Hao Tan

