Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Number class problem

 
Saurabh Khanna
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Folks

Both wrapper classes Long and Integer extend Number class.

If i use the following code:



Why does it print unequal even though the value inside both the objects is really equal (that is 4) ???

Thanks in advance.

regards
Saurabh
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because they're two different classes, and that's how their equals() methods are implemented. Would you want a JButton labelled "OK" and a JRadioButton labelled "OK" to compare equal?
 
Saurabh Khanna
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ernest

Hmmm, that makes sense. I would'nt want JButton and JRadioButton to compare equal. However, one would expect the wrapper classes to exhibit same sort of behaviour as the primitives, well thats obviously not the case as you explained above.

For example, the following code prints equals:



How can i get the above effect using wrapper classes?

regards
Saurabh
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could call longValue() on each Number, and compare those values using "==".
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic