Adding an object to multiple java collections: does it make multiple copies?

If I add the same object to two different collections, does it 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 let me use different methods to access and order objects.

+4
source share
1 answer

No, adding an object to the collection, you simply pass a link to this object (the address where the object is stored on the heap). Thus, adding one object several times to different collections is like distributing business cards, you do not duplicate yourself, but several people know where to find you;)

Here is the 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 
+10
source

Source: https://habr.com/ru/post/1445654/


All Articles