为什么将图像复制到一个新变量中不会复制数据,而只会复制指针?

huangapple go评论78阅读模式
英文:

Why coping an image into a new variable doesn't copy data but pointer?

问题

当我像这样做一些事情时:

BufferedImage image = otherImage;

而且 image 被影响时,otherImage 也会受到影响吗?

英文:

When i do something lile this:

BufferedImage image = otherImage;

and image got affected otherImage get affected too?

答案1

得分: 1

这就是 Java 内存模型的工作原理。
所有的对象都被放置在堆中。在方法帧中,您只能通过引用访问链接来引用这些对象。您可以通过这些链接来操作对象。
您发布的语句表明您想要获取第二个链接,并将其引用到与第一个链接引用的相同对象。

如果您需要复制对象,您需要自行关心。有几种方法可以实现这一点。
例如,您可以创建一些复制方法,该方法将获取初始对象,获取其字段,创建一个新实例,并将这个新创建的对象的字段设置为之前提取的字段。

更新:请查看这个链接,其中解释了关于 BufferedImage 的具体情况。但似乎问题需要更新并标记为重复。

英文:

This is how java memory model works.
All objects placed in a heap. In your methods frames you only have an access to link that refers to this objects. You can manipulate with objects via this links.
Statement that you posted says that you want take the second link and refer it to the same object as first link refers.

In case you need to copy object you need to care about that by yourself. There are a few ways to achieve this.
For example you can make some copying method that will take initial object, take it’s fields, create a new instance, and set fields of this newly created object to previous extracted ones.

UPD: Take a look into this. There are explanations for your concrete case with BufferedImage. But seems like the question need to be updated and marked as duplicate.

huangapple
  • 本文由 发表于 2020年10月12日 05:35:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/64309247.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定