How many instances are stored for an item in two different collections?

If I have an instance of MyClass, call it myElement and add it to the two lists, or in the queue, or to the cards or something else. How many times will it be stored in memory?

MyClass myElement = new MyClass();

List<MyClass> list1  = new ArrayList<MyClass>();
PriorityQueue<MyClass> queue1 = new PriorityQueue<MyClass>();

list1.add(myElement);
queue1.add(myElement);

Will it be saved only once, and both list items indicate this location in memory? Or will I save it twice?

+3
source share
2 answers

No matter how many added lists you add, there is only one instance.

In short. So there is only one.

+7
source

you call the class reference. he will always point to the same place of memory, wherever you are.

only one instance will exist.

0
source

All Articles