File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Number class problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Number class problem" Watch "Number class problem" New topic
Author

Number class problem

Saurabh Khanna
Ranch Hand

Joined: Apr 03, 2005
Posts: 30
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

Joined: Jul 08, 2003
Posts: 24183
    
  34

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?


[Jess in Action][AskingGoodQuestions]
Saurabh Khanna
Ranch Hand

Joined: Apr 03, 2005
Posts: 30
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

Joined: Jul 08, 2003
Posts: 24183
    
  34

You could call longValue() on each Number, and compare those values using "==".
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Number class problem