YoungCoconutCode YoungCoconutCode - 6 months ago 26
Java Question

Android lists (ArrayList, List, etc.): addAll() vs redefining reference

If I have something like:

ArrayList<Data> mList = new ArrayList();

...

public void setList(ArrayList<Data> list) {
mList = list;
}


public void updateList(ArrayList<Data> list) {
mList.clear();
mList.addAll(list);
}


Which is more efficient,
setList()
or
updateList()
and why? What is the best practice?

EDIT:

Not to be confused with this question.

Answer

There is an enormous conceptional difference between the two.

Your setList() takes a reference to a list; and changes your mList ... to point to that reference.

Whereas your updateList() copies all the references from the incoming list into your existing mList object.

Meaning: setList() does require less CPU operations compared to updateList() ... but the key thing is: now mList can be changed from outside of your class. Like in:

List someList = ...
yourClass.setList(someList);
someList.clear();

will clear "your" mList as well; but

List someList = ...
yourClass.updateList(someList);
someList.clear();

will not affect your "mList".

That's the main difference you should be aware of.

Performance is actually not the real issue to be concerned about here!

In general: do not worry too much about performance. Because: you will not get it right anyway. For example, there is the JIT compiler turning naive assumptions upside down.

Long story short: focus on semantics of operations; don't restrict yourself to "performance" aspects.