Scala中==、eq、ne和equals的区别

官方API定义:

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

//表达式x==that含义为:如果x eq null 则为that eq null 否则为x.equals(that)

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

//测试参数(that)是否是对接收方对象(this)的引用。

  • def equals(arg0: Any): Boolean
    Compares the receiver object (this) with the argument object (that) for equivalence. 

// 比较接收方对象(this)与参数对象(that)的等价性。

  • 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.

//相当于!(this eq that).如果参数不是对接收方对象的引用,则返回true;否则返回false。

总结

  • 如果要比较对象的引用是否相同或者不同,使用eq或ne方法
  • 如果要比较值是否相等,使用equals方法或者==方法,推荐使用==方法,因为如果比较值为null的情况下,调用equals方法会报错,而==方法则避免了这个问题,它事先检查了值是否为null,然后再进行比较。
     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Oak-Komorebi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值