Reputation: 19
Can I add an object to an ArrayList
without a reference?
For example, can I add object as below:
ArrayList<Dog> list=new ArrayList<Dog>();
list.add(new Dog);
Upvotes: 0
Views: 2964
Reputation: 4873
Yes you can.
If you don't reference the new dog anywhere else, it will be up for garbage collection as soon as the list is eligible for garbage collection. See also this answer.
In addition to the other suggested improvements to your example code, you should
List
over ArrayList
(see Why should the interface for a Java class be preferred?)Your code would then look like this:
List<Dog> list = new ArrayList<>();
list.add(new Dog());
Upvotes: 0
Reputation: 26961
You cannot do this:
list.add(new Dog);
but this:
list.add(new Dog());
Why can this be done?
Actually is quite simple, JVM
will automatically keep a reference of the created object inside the List
to keep it alive, so you don't have to care about. As usual, if this object is removed from the list and not referenced anywhere else, will be elegible for Garbage Collector
.
Upvotes: 3
Reputation: 4037
Yes, you can. Once you add the object to arrayList, what matters in only where the object is in the heap. It does not matter, you add it with reference or without.
But yes, it should be list.add(new Dog())
.
You are missing the paranthesis after Dog
.
Upvotes: 1