Home > Software engineering >  Are 2 references to an object == to each other?
Are 2 references to an object == to each other?

Time:11-28

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?

CodePudding user response:

The == checks if objects p and moved are the same object. Since you created a new object (p = new Point), moved will not be the same object even if it has the same values.

If you want to compare values, you can use equals(). So: Assertions.assertTrue( p.equals(moved) );

CodePudding user response:

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);
    }
}
  • Related