scala的==、equals、eq、ne区别与用法

根据官方API的定义:

final def ==(arg0: Any): Boolean
The expression x == that is equivalent to if (x eq null) that eq null else x.equals(that)

final def eq(arg0: AnyRef): Boolean
Tests whether the argument (that) is a reference to the receiver object (this)

def equals(arg0: Any): Boolean
The equality method for reference types

简言之,equals方法是检查值是否相等,而eq方法检查的是引用是否相等。所以如果比较的对象是null那么==调用的是eq,不是null的情况调用的是equals。

***final def eq(arg0: AnyRef): Boolean***
  Tests whether the argument (that) is a reference to the receiver object (this).

  The eq method implements an equivalence relation on non-null instances of AnyRef, and has three additional properties:

  It is consistent: for any non-null instances x and y of type AnyRef, multiple invocations of x.eq(y) consistently returns true or consistently returns false.
For any non-null instance x of type AnyRef, x.eq(null) and null.eq(x) returns false.
null.eq(null) returns true.
When overriding the equals or hashCode methods, it is important to ensure that their behavior is consistent with reference equality. Therefore, if two objects are references to each other (o1 eq o2), they should be equal to each other (o1 == o2) and they should hash to the same value (o1.hashCode == o2.hashCode).
returns
true if the argument is a reference to the receiver object; false otherwise.

简而言之,这里eq方法进行的是引用比较,比较两个对象的引用是否相同

***final def ne(arg0: AnyRef): Boolean***
  Equivalent to !(this eq that).
  returns true if the argument is not a reference to the receiver object; false otherwise.

ne方法是eq方法的反义

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值