Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Avoiding Passing by Reference

I have made a Line class in Java, and I also have a drawing class with a method in it that draws that Line to the screen; when I call that method, it also centers the Line, and once the method is finished, it edits the value of the original Line.

A non-ideal solution I have thought of is de-centering the Line to change its value back, but I have a lot more stuff than just a Line and a drawing class in this project, and I would like to know a way to avoid this problem for good. In C++, I know that you can send parameters by address or by pointer, and to the best of my knowledge, you can't do that in Java, but if there's anything similar to that, that could possibly be the best solution.

This is the code for the method to draw the Line on the screen.

public void drawLine(Line ln) {
    //I have used a new variable to try to avoid the problem, but it doesn't work.
    Line buf = new Line();
    buf.begin = ln.begin;
    buf.end = ln.end;

    buf.begin = centerPoint(buf.begin);
    buf.end = centerPoint(buf.end);
    gfx.drawLine((int) buf.begin.x, (int) buf.begin.y, (int) buf.end.x, (int) buf.end.y);
}

Here is how I am using the Line

    Line ln = new Line(0, 0, 100, 0);
    draw.drawLine(ln);
    System.out.println(ln.begin.x + ", " + ln.end.x);
    //It should print 0, 0, but instead it prints out a different number, because it has been centered.

Thanks for your help.

like image 906
foo bar Avatar asked Jul 04 '26 11:07

foo bar


1 Answers

It looks like your problem is that the state of the ln.begin and ln.end instances is changed by the centerPoint method.

You can avoid that if buf.begin and buf.end would be copies of those instances instead of referring to them.

public void drawLine(Line ln) {
    Line buf = new Line();
    buf.begin = new Point(ln.begin); // I'm guessing the class name and available constructor
    buf.end = new Point(ln.end); // I'm guessing the class name and available constructor

    buf.begin = centerPoint(buf.begin);
    buf.end = centerPoint(buf.end);
    gfx.drawLine((int) buf.begin.x, (int) buf.begin.y, (int) buf.end.x, (int) buf.end.y);
}
like image 180
Eran Avatar answered Jul 07 '26 01:07

Eran