Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Java store objects in a List?

Tags:

java

list

I have to work with an existing application and there is a List which stores all rendered objects in order to remove them later if the gui changes.

This is the List:

private List<Component> registeredComponents = new ArrayList<Component>();

Now I'm wondering if Java only stores references to the objects (ZK components) or if it does store a copy of the objects. The question is if I should remove this.

like image 704
mw88 Avatar asked Jun 16 '11 09:06

mw88


2 Answers

The list will contain references only. This holds for all types of collections, not only ArrayLists.

In Java there's actually no way to "get hold of" the object itself. When you create a new object all you get is a reference to it (and there's no way to "dereference" it by using for instance a * operator as in C++).

like image 192
aioobe Avatar answered Oct 08 '22 19:10

aioobe


The List stores references to the objects, not a copy. The object instances are shared with anyone else who happens to have another reference to them.

As for wanting to remove this, if you have another way to remove the objects from the GUI later (maybe you can query a parent component or something), the List may be redundant. But even if it is, there is probably not much overhead here, and not having it might be complicating your program.

like image 45
Thilo Avatar answered Oct 08 '22 19:10

Thilo