Daniel Bastos
Daniel Bastos

Reputation: 143

Changing a reference in Java

I'm trying to develop a Data Structure in Java and I'm facing a problem that I just can't solve. I have a reference to an object, and, after copying it, I want to change the original reference using only the copy. For example:

Point a = new Point(0,0);
Point b = a;
b = new Point(5,5);

I want "a" to point to "new Point(5,5)" too, and not only "b". Is there anyway to do that?

Thanks for the help.

Upvotes: 1

Views: 525

Answers (4)

davioooh
davioooh

Reputation: 24706

When you create the new Point(5,5), a new reference is assigned to b, so you'll have different references for a and b.

The only way to mantain a reference to the same instance, so that changes to b are "visible" also to a, is to set new values (5,5) to the original object (as also explained from Alderath):

b.setX(5);
b.setY(5);

Upvotes: 0

Alderath
Alderath

Reputation: 3874

If you make setter methods you could do:

Point a = new Point(0,0);
Point b = a;
//b and a now reference the same point
b.setX(5);
b.setY(5);
//Now we have made changes to the point referenced by b
//Since a references the same point, these changes will
//also apply to a

The problem with your example is that you are doing new Point(x,y).

Point a = new Point(0,0);
Point b = a;
//At this point only one instance of Point exists.
//Both a and b reference the same Point.
//Any change you do to that point will be reflected through both a and b.
b = new Point(5,5);
//Now you have created a second instance of point.
//a and b reference the different points.

So, in summary, you must understand the difference between modifying the already existing point and creating a new point and letting only one of the references reference the new point.

Upvotes: 2

Pablo
Pablo

Reputation: 3673

You can't do that in Java. You could simulate it creating a wrapper for Point:

public class PointWrapper {
    private Point point;

    public PointWrapper(Point point) {
        this.point = point;
    }

    public Point getPoint() {
        return point;
    }

    public void setPoint(Point point) {
        this.point = point;
    }
}

PointWrapper a = new PointWrapper(new Point(0,0));
PointWrapper b = a;
b.setPoint(new Point(5,5));

Upvotes: 0

gefei
gefei

Reputation: 19846

Point a; // no need to instantiate
Point b = new Point(5,5);
a = b;

Upvotes: 4

Related Questions