• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Uniqueness of objects

 
Gary McGath
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Joe Ess
Bartender
Posts: 9313
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can't duplicate it.

Results:
 
John Smith
Ranch Hand
Posts: 2937
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
should be the case only if the Objects you're creating are Strings that are initialised to String literals containing the same literal.
Like
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic