BruceEckel / OnJava8-Examples

Code Examples for the book "On Java 8"

Home Page:http://www.OnJava8.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Testing Object Equivalence

altgeek opened this issue · comments

The output is:
/* Output:
true
false */

"Surely the output should be “true”, then “false,” since both Integer objects are the same."

This is the case, I tested it.

The book says "the output is actually “false”, then “true.”"

This doesn't match the output.

If I used new Integer ( 47 ) on the assignment for n1 and n2, then your second statement works.

(p.s. I am aware of the Integer cache for values -128 to 127 , so the simple example in the book has even more unwanted nuances.)

Ref altgeek above: Was also confused by this. If the values assigned to the Integer objects are outside the -128 to 127 range, then the output will match the text explanation. The values used (47) causes it to fall into the exception due to cached numbers. So there are two learning opportunities here: equivalence of references vs values and the existence of the Integer class cache. As noted above, if you force the object to its own reference with the "new Integer", the text also holds as written.

From an email:

Hi Bruce,

I noticed an error on your book on Testing Object Equivalence

Initializing Integer n1 = 47 and Integer n2 = 47 will go as true and false in the comparison you make, however when initialized with Integer n1 = new Integer(45) and Integer n2 = new Integer(45) will produce the false and true output as described.

I guess there should be an update there on the “new” initialization.

Best regards,
Dragos

Fixed. Examples are available now, prose will appear in next Leanpub update but can be found here: https://www.bruceeckel.com/2021/02/04/java-object-equivalence/

Fixed. Examples are available now, prose will appear in next Leanpub update but can be found here: https://www.bruceeckel.com/2021/02/04/java-object-equivalence/

Bruce, is there any upgrade path for the newest/corrected edition for those of us that bought the initial release on google books?