What is the difference between being shallowly and deeply equal? How is this applied to caching?

后端 未结 5 1828
轻奢々
轻奢々 2020-12-15 12:38

Found the following in my notes, but I am unable to make sense of it:

Primitive type wrapper classes implement caching for a limited number of value

5条回答
  •  没有蜡笔的小新
    2020-12-15 13:15

    Well, actually shallow/deep dissection is different from ==/equal dissection:

    1. == compares for object identity, that is you checking whether operands are the same in fact (two references to the same area of memory), whereas equals compares for object equivalence, that is "logical" value of two, possibly not identical objects, is the same. If for two objects

      a == b
      

      then it's true that

      a.equals(b) // if a != null
      

      , but opposite isn't true in all cases.

    2. shallow/deep distinction makes sense only for equals comparison. Shallow means that you compare only immediate contents of two objects to find whether they "equal" in your sense, whereas deep means that you compare contents of your objects recursively until all you need to compare is primitive fields. If you define equals method of your objects as sequence of calls to equals on instance fields of these objects, you use deep comparison. If you define equals using == operator to compare compound types, such as Strings, then you use shallow comparison -- and that's incorrect in Java.

    Morale of all of this is that you must never use == to compare two compound objects, unless you consider them equal only if they are the same.

提交回复
热议问题