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?
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?