I was messing the Java's Point2D.Double class and ran into some issues with changing the values of points when set equal to one-another first.
This is how Points work in Java:
/** Testing with Points */
System.out.println("Points: ");
// Create a new point:
Point2D.Double point1 = new Point2D.Double(1, 1);
System.out.println(point1);
// Create another new point, based on the old point
Point2D.Double point2 = point1;
System.out.println(point2);
// Change point1, print both again.
point1.setLocation(0, 1);
System.out.println(point1);
System.out.println(point2);
The output of that code would be:
Points: Point2D.Double[1.0, 1.0]Point2D.Double[1.0, 1.0]Point2D.Double[0.0, 1.0]Point2D.Double[0.0, 1.0]
Notice point2 ends up with the value [0.0, 0.0], even though the only point changed was point1?
Here is the same code again, but with primitive integers:
/** Testing with Integers */
System.out.println("Integers: ");
// Create a new integer (primitive)
int integer1 = 1;
System.out.println(integer1);
// Create another new integer (primitive), based on the old int.
int integer2 = integer1;
System.out.println(integer2);
// Change integer1, print both again.
integer1 = 0;
System.out.println(integer1);
System.out.println(integer2);
The output of this code would be:
Integers: 1101
Only the Point2D class seems to carry values from class to class like that. The Point2D documentation for the setLocation function reads:
Sets the location of this Point2D to the specified double coordinates.
Notice the word THIS
I was actually able to work around this problem with this code:
Point2D.Double point2 = new Point2D.Double(point1.x, point1.y);
but I still want to understand why the Point2D class works this way and what other classes have this same property.
Thank you for reading, I look forward to reading your responses.