1. 程式人生 > >scala的==、equals、eq、ne區別與用法

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方法的反義