This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Java in General and the fly likes Uniqueness of objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Uniqueness of objects" Watch "Uniqueness of objects" New topic
Author

Uniqueness of objects

Gary McGath
Ranch Hand

Joined: Mar 15, 2003
Posts: 52
I've always assumed that if you call new(Classname) on two separate occasions, you get two distinct objects, which will never be == to each other. In chasing down a recent bug, though, it appears that this isn't always the case.
The class which I created is called Rational. It looks something like this:
public class Rational {
int num;
int denom;
public Rational (int n, int d) {
num = n;
denom = d;
}
/* The obvious accessors .... */
}
If I call
Rational a = new Rational (0, 1);
Rational b = new Rational (0, 1);
Then I find that (a == b) is true!!
If I then call a.setNum (2), (a == b) is no longer true.
It appears that the JVM is doing some very strange optimization. (I'm using the Sun JDK 1.4.2 on Windows; I haven't tested this on other platforms.)
The == test makes a difference because I'm using Rational leaf nodes in a JTree, and using an == test to locate a child relative to its parent.
Could this have something to do with a Rational being a very small object, which can in principle be stored in just 64 bits?


http://www.mcgath.com/consulting/
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8876
    
    8

I can't duplicate it.

Results:


"blabbing like a narcissistic fool with a superiority complex" ~ N.A.
[How To Ask Questions On JavaRanch]
John Smith
Ranch Hand

Joined: Oct 08, 2001
Posts: 2937
It appears that the JVM is doing some very strange optimization. (I'm using the Sun JDK 1.4.2 on Windows; I haven't tested this on other platforms.)
I am also using 1.4.2 under Windows, but I cannot reproduce your problem. Can you reduce your class to an absolute minimum and post your complete test code?
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
should be the case only if the Objects you're creating are Strings that are initialised to String literals containing the same literal.
Like


42
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Uniqueness of objects