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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With