David Shnaiderov
David Shnaiderov

Reputation: 11

Aliasing doesn't work

I created this class with the method addVertex:

public class Polygon {
    private PointNode _startPoint;

    public Polygon() {
        _startPoint = null;
    }

    public boolean addVertex(Point p, int pos) {
        PointNode next = _startPoint;
        int i = 0;
        while(i != pos){
            if(next == null)
                return false;
            next = next.getNext();
            i++;
        }
        next = new PointNode(p);
        return true;
    }
}

But the problem is that next doesn't alias with _startPoint and because of that I can only use the method when pos == 0 but if pos >= 1 then it always returns false even after I set a value in position 0 of the list I created.

Can someone tell me where the problem is?

Upvotes: 1

Views: 106

Answers (1)

gvlasov
gvlasov

Reputation: 20035

In Java, you can't change what object a variable is pointing to other than by assigning another object to that exact variable with =. So, the only way to put another object to _startPoint is to actually do:

_startPoint = someOtherObject;

So, in Java, you can't give multiple names to a variable, as with PHP's & construct, for example.

Upvotes: 2

Related Questions