• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

error in roundup?

 
jaco hoff
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think I may have found an error in the cow roundup. I forgot the question number though, so I can't look it up again. The question was if 2 Integers with value 5 are '=='. The correct answer is yes. Shorts and Integers with a value between -128 and 127 are considered '==', even if they are different objects. With another value they are not '==', but are 'equals'. (Not good English, but I think you know what I mean).
Can someone please confirm if that question was incorrect?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34229
341
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jaco,
Welcome to JavaRanch!

The roundup was written before Java 5 came out. Java 5 introduced generics where the behavior you describe was introduced. Before that, comparing two Integers was like comparing two Objects - where you had to use equals().

There was a discussion in this forum recently about upgrading the roundup for Java 1.4. I don't recall the outcome.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm quite sure (without having really tried it) that

new Integer(5) != new Integer(5)

even in Java 5, *but*

Integer.valueOf(5) == Integer.valueOf(5)

That is, the valueOf method (which is also used by autoboxing) does the caching. The constructor simply can't, technically - two calls *have* to create two distinct objects.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34229
341
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ilja Preuss:
I'm quite sure (without having really tried it) that ...

For what it's worth, I just tried it. You are correct.
 
jaco hoff
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so
Integer i1 = 5;
Integer i2 = 5;
System.out.println(i1 == i2);
returns true.
and

Integer i1 = new Integer(5);
Integer i2 = new Integer(5);
System.out.println(i1 == i2);
returns false.

Nasty little details. Thanks for the replies
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic