gpt4 book ai didi

java - 为什么 Point2D 的值有时表现为静态?

转载 作者:行者123 更新时间:2023-12-01 13:33:39 25 4
gpt4 key购买 nike

我弄乱了 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]

注意到 point2 最终的值为 [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 文档如下:

Sets the location of this Point2D to the specified double coordinates.

注意这个词这个

<小时/>

我实际上能够使用以下代码解决这个问题:

Point2D.Double point2 = new Point2D.Double(point1.x, point1.y);

但我仍然想了解为什么 Point2D 类以这种方式工作,以及其他哪些类具有相同的属性。

感谢您的阅读,我期待阅读您的回复。

最佳答案

Point2D.Double 是一个类。您仅创建该对象的一个​​实例。因此,通过使用:

Point2D.Double point2 = point1;

您只是创建一个“指针”,它指向与第一个对象相同的内存。在第二个示例中,您创建了 Point 对象的两个不同实例。

请看我画得不好的图片。

Point references

关于java - 为什么 Point2D 的值有时表现为静态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21409657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com