Marvin Meller Marvin Meller - 7 months ago 32
Java Question

How to return and clear a list?

I've wondered if there is a more elegant approach to return an attribute and change/"reset" its value. This is the way I've been doing it by now:


final List<T> copyOfOriginal = new ArrayList<T>(original);

return copyOfOriginal;


Do I really have to copy the whole list?


In many cases one can simply replace the list with a new empty one while returning the original reference:

final List<T> ret = original;
original = new ArrayList<T>();
return ret;

The caveat here is that this changes the original references. If there are multiple copies of it, this might require extra care.