Java集合如何节省元素(浅或深)

发布于 2025-01-28 22:27:05 字数 85 浏览 5 评论 0 原文

在Java集合(数组,linkedlist,set)中,当添加对象时,是否保存参考的副本或将整个对象复制到集合中。如果我更改原始对象,它会影响集合的对象吗?

In the Java collections (array, LinkedList, Set), when an object is added, does it saves a copy of the reference or copy the entire object to the collection. And if I change the original object does it effect the collection's object?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

国粹 2025-02-04 22:27:05

在添加对象时,在Java集合(数组,linkedlist,set)中是否保存参考的副本或将整个对象复制到集合。

它保存了参考。它不会复制对象。

可以从对于 collection.add 方法:

布尔值add(e e)

确保此集合包含指定的元素。如果此集合因呼叫而更改。

返回true。

请注意,该集合表示该集合将包含指定元素的指定元素...而不是指定元素的副本

如果我更改了原始对象,它会影响集合的对象吗?

是的。它们是相同的对象。

In the java collections (Array , LinkedList , Set) when an object is added does it saves a copy of the reference or copy the entire object to the collection.

It saves a reference. It does not copy the object.

This can be inferred from the javadoc for the Collection.add method:

boolean add(E e)

Ensures that this collection contains the specified element. Returns true if this collection changed as a result of the call.

Notice that it says that the collection will contain the specified element ... not a copy of the specified element.

If i change the original object does it effect the collection's object?

Yes. They are the same object.

美胚控场 2025-02-04 22:27:05

是的,如果更改原始对象,它确实会更改集合中的对象。

您可以在此处阅读一个类似的问题,该问题谈论Java是通过参考: java”是“通过参考”还是“通过逐个价值”?

Yes, if you change the original object it does change the object inside the Collection.

You can read a similar question here which talks about java being a pass by reference: Is Java "pass-by-reference" or "pass-by-value"?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文