Java - avoid traversing a link
I created a Line class in Java and I also have a draw class with a method in it that draws this Line on the screen; when i call this method, it centers the string as well, and once the method is finished, it edits the value of the original string.
The imperfect solution I thought of is decentizing the line to change its value back, but I have a lot more stuff than just line and drawing class in this project and I would like to know to avoid this problem forever. In C ++, I know that you can send parameters by address or by pointer, and as far as I know, you cannot do this in Java, but if something is similar to this, this might be a better solution.
This is the method code for drawing a 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);
}
This is how I use 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.
Thank you for your help.
source to share
It looks like your problem is that the state of the instances ln.begin
and is ln.end
changed with the method centerPoint
.
You can avoid this by making buf.begin
u buf.end
copies of these instances rather than 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);
}
source to share