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

后端 未结 5 1604
轻奢々
轻奢々 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:16

    First off: new Integer(0) == new Integer(0) will never evaluate to true, as new always creates a new object, sidestepping any autoboxing-caching mechanism that might exist.

    What you probably heard about was autoboxing (i.e. automatic conversion of primitive values to their respective wrapper classes when necessary). Autoboxing uses a mechanism that's also accessible using the wrapper classes valueOf() methods. In other words: auto-boxing an int to an Integer works pretty much the same as calling Integer.valueOf(int).

    Integer.valueOf(0) == Integer.valueOf(0) will evaluate to true, because common values (i.e. values with a low absolute value) are cached. You'll get the same Integer object when you call valueOf(0) twice in a row. This is not necessarily true with higher values (such as 666 in your example).

提交回复
热议问题