1

I have a list that used for adapter for ListView in Android.

Most time, the List is used for read but sometimes replace of all List contents is needed.

which type of code below (replaceListA, replaceListB) is preferred? or another way to replace the list?

thank you in advance.

private ArrayList<Model> list = new ArrayList<Model>();

public synchronized void replaceListA(List newList) {
            list.clear();
            list.addAll(newList);
}

public synchronized void replaceListB(List newList) {
    list = newList;
}
Kent
  • 13
  • 3

3 Answers3

1

See this answer.

It's hard to know without a benchmark, but if you have lots of items in your ArrayList and the average size is lower, it might be faster to make a new ArrayList.

Community
  • 1
  • 1
mattbdean
  • 2,532
  • 5
  • 26
  • 58
1

In general, replaceListB will probably run faster, but if newList is later modified, list will also change. For example:

ArrayList<Model> newList = new ArrayList<Model>();
replaceListB(newList);
newList.add( /*something*/ ); //This will update both newList and list

By contrast

ArrayList<Model> newList = new ArrayList<Model>();
replaceListA(newList);
newList.add( /*something*/ ); //This will only update newList

To be more specific, replaceListB will run in a constant amount of time, since it is only changing a pointer, where replaceListA has to copy over each element of the list individually, so it will take a long time if the list is large. However, depending on the details of the garbage collecter, it's possible that replaceListA could free up memory sooner. Either way, it is unlikely to make a major difference unless the lists are very large, so I would recommend choosing based on whether you want to make a separate copy of the list (replaceListA) or allow editing (replaceListB).

Flight Odyssey
  • 2,267
  • 18
  • 25
0

The second is preferred. It runs in O(1) time, the other runs in O(n) time. Just be sure to call notifyDataSetChanged afterwards.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127