简体   繁体   English

将对象添加到多个java集合中:这是否会生成多个副本?

[英]Adding an object to multiple java collections: Does this make multiple copies?

If I add the same object to two different collections, does that make a copy of the object in each collection, or do the collections get references to the same object? 如果我将同一个对象添加到两个不同的集合中,是否会在每个集合中复制该对象,或者集合是否会引用同一个对象?

What I'm trying to do is use two different collections to manage the same set of objects, but allow me different methods to access and order the objects. 我想要做的是使用两个不同的集合来管理同一组对象,但允许我使用不同的方法来访问和排序对象。

No, by adding an object to a collection, you are just passing the reference to that object (the address where the object is stored on the heap). 不,通过向集合添加对象,您只是将引用传递给该对象(对象存储在堆上的地址)。 So adding one object multiple times to different collections is like handing out business cards, you're not duplicating yourself but multiple people know where to find you ;) 所以多次将一个对象添加到不同的集合中就像分发名片一样,你不是自己复制,而是多个人知道在哪里找到你;)

Here some code: 这里有一些代码:

LinkedList<MyObject> list1 = new LinkedList<MyObject>();
LinkedList<MyObject> list2 = new LinkedList<MyObject>();
MyObject obj = new MyObject();
list1.add(obj);
list2.add(obj); // This does not create a copy of the object, only the value of the address where to find the object in the heap (memory) is being copied

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM