Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 785
djc6535 Avatar asked Nov 12 '12 23:11

djc6535


1 Answers

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
like image 188
das_weezul Avatar answered Nov 15 '22 11:11

das_weezul