File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Wrapper equality

 
Aniket Patil
Ranch Hand
Posts: 218
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Accroding to the rules of Wrappers,

Integer i1 = 127;
Integer i2 = 127;

i1 == i2, returns True.

However,
Integer i1 = new Integer(127);
Integer i2 = 127;

OR

Integer i1 = new Integer(127);
Integer i2 = new Integer(127);

i1 == i2, returns False in both cases.

Is this because using new( ) creates a fresh object on the heap, ignoring another object with the same value that might exist on the heap?
[ September 11, 2006: Message edited by: Aniket Patil ]
 
wise owen
Ranch Hand
Posts: 2023
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The API tells you:
Integer

public Integer(int value)

Constructs a newly allocated Integer object that represents the specified int value.

Parameters:
value - the value to be represented by the Integer object.



You might like to comare it with valueOf:
valueOf

public static Integer valueOf(int i)

Returns a Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values.

Parameters:
i - an int value.
Returns:
a Integer instance representing i.
Since:
1.5

 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,


valueOf can be tricky as well:


prints false.
If both parameters were integer literals, it would be true.

Yours,
Bu.
 
Meena R. Krishnan
Ranch Hand
Posts: 178
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


print false. How?
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by M.R.Krishnan:


print false. How?


Have you checked the API? The caching version of valueOf was recently added in Java 5.0.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic