You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala中Seq与Array的==比较行为差异及原因探究

Why 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 sameElements method 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:07:07