我弄乱了Java的Point2D.Double类,并且在设置等于另一个时,遇到了更改点值的一些问题。
这就是Points在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);
该代码的输出为:
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]
注意点2最终得到值[0.0,0.0],即使唯一改变的点是point1?
这里再次使用相同的代码,但是使用原始整数:
/** 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);
此代码的输出为:
Integers: 1101
只有Point2D类似乎会在类之间传递值。 setLocation函数的Point2D文档为:
将此Point2D的位置设置为指定的双坐标。
请注意 THIS
这个词我实际上可以使用此代码解决此问题:
Point2D.Double point2 = new Point2D.Double(point1.x, point1.y);
但我仍然想了解为什么Point2D类以这种方式工作以及其他类具有相同的属性。
感谢您的阅读,我期待着您的回复。
答案 0 :(得分:1)
Point2D.Double是一个类。您只创建该对象的一个实例。 所以通过使用:
Point2D.Double point2 = point1;
您只创建一个“指针”,它指向SAME内存作为第一个对象。 在第二个示例中,您将创建Point对象的两个不同实例。
请看我画得不好的图片。
答案 1 :(得分:0)
我认为你混淆了引用和实例(对象)。 point1是对实例的引用,您将point2作为对同一实例的引用。修改实例时,指向哪个引用无关紧要。
对于新的Point2D.Double(point1.x,point1.y),您正在创建一个新实例。
如果是整数,您也在使用新实例。
答案 2 :(得分:0)
point1和point2引用同一个对象。如果您更改了一个,则更改两者,除非您使用找到的new
。
它适用于int,因为int是原始数据类型,因此没有它的实例。
阅读本文以获取有关java指针,引用和传递参数的更多信息。