8

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.

1
  • perhaps off-topic but useful to know when working with collections (list, set, etc.): you'll probably want to use methods like contains(), add() on your list but these will only work if the object inside (your Component class) overrides the equals() and hashcode(). (Most IDEs have feaures to generates these for you). If you don't then it will compares the object reference and not its content... Commented Jun 16, 2011 at 9:58

2 Answers 2

13

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++).

Sign up to request clarification or add additional context in comments.

4 Comments

you may "get hold of" the object itself by deep copy by overriding the clone() method for example
No, you'll end up with a reference to a copy of the object.
It's by default. You may override the behaviour. See java2s.com/Code/Java/Language-Basics/DeepCopyTest.htm
I don't think you understand. There is no way a variable (or collection) can hold an object. It can only contain references to objects (no matter what methods you override or how you create your objects).
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.