Skip to content
Advertisement

Are 2 references to an object == to each other?

I have a method, move(xSteps, ySteps), which takes a point and moves it according to the parameters on the method by increasing or decreasing x and y.

But when the xSteps and ySteps are both 0, I want to store the moved point (which didn’t actually move) in the same memory location as the original point since the x and y value should be the same.

The move method is below

public Point move(int xSteps, int ySteps) {
    Point p;
    Point p2;
    if (xSteps == 0 && ySteps == 0) {
        p = new Point(x, y);
        p2 = p
        return p2;
    } else {
        p2 = new Point(x + xSteps, y + ySteps);
    }
    return p2;
}

However when i run this test,

moved = point.move(0,0);

        Assertions.assertTrue(p == moved);

It returns false, but it should be true. Why is this happening?

Advertisement

Answer

p == moved tests whether p and moved reference the same object.

Since the move() method always returns a new Point() this test will fail with your current implementation of the move() method.

If you want to store the moved point (which didn’t actually move) in the same memory location as the original point then you need to change your move method to

public Point move(int xSteps, int ySteps) {
    if (xSteps == 0 && ySteps == 0) {
        return this;
    } else {
        return new Point(x + xSteps, y + ySteps);
    }
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement