djc6535
djc6535

Reputation: 1944

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.

Upvotes: 5

Views: 3111

Answers (1)

das_weezul
das_weezul

Reputation: 6142

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

Upvotes: 12

Related Questions