官术网_书友最值得收藏!

Referential equality and structural equality

When working with a language that supports object-oriented programming (OOP), there are two concepts of equality. The first is when two separate references point to the exact same instance in memory. The second is when two objects are separate instances in memory but have the same value. What the same value means is specified by the developer of the class. For example, for two square instances to be the same, we might just require they have the same length and width regardless of coordinates.

The former is called referential equality. To test whether two references point to the same instance, we use the === operator (triple equals) or !== for negation:

    val a = File("/mobydick.doc") 
    val b = File("/mobydick.doc") 
    val sameRef = a === b 

The value of the test a === b is false because, although a and b reference the same file on disk, they are two distinct instances of the File object.

The latter is called structural equality. To test whether two objects have the same value, we use the == operator or != for negation. These function calls are translated into the use of the equals function that all classes must define. Note that this differs from how the == operator is used in Java—in Java, the == operator is for referential equality and is usually avoided:

    val a = File("/mobydick.doc") 
    val b = File("/mobydick.doc") 
    val structural = a == b 

Note that, in the double equals check, the value was true. This is because the File object defines equality to be the value of the path. It is up to the creator of a class to determine what structural equality means for that class.

The == operator is null safe. That is, we don't need to worry if we are testing a null instance as the compiler will add the null check for us.
主站蜘蛛池模板: 通许县| 翼城县| 罗定市| 友谊县| 卓尼县| 海淀区| 永善县| 天水市| 长治县| 长泰县| 蒙城县| 沈阳市| 读书| 托里县| 韶山市| 广宗县| 西乡县| 和田县| 玉龙| 中宁县| 长垣县| 容城县| 柳州市| 葫芦岛市| 济南市| 南靖县| 仪陇县| 通道| 乌拉特前旗| 浦县| 洪江市| 龙南县| 铁岭县| 富平县| 淮滨县| 鄯善县| 化州市| 许昌市| 富锦市| 阜康市| 辽源市|