How to return and clear a list?

Marvin

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);
original.clear();

return copyOfOriginal;

[...]

Do I really have to copy the whole list?

NPE

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related