0

If I need to retrieve some collection of objects (assume its some Client), lets say from DB. So there are two possibilities:

1 in some class-receiver I would declare like:

...
 private final List<Client> clients = new ArrayList<Client>();
...
// the fillinng method:
fillClients(){
   dbHelper.getClients(clients);
}

So dbHelper's method will receive a ready to use collection it would NOT CREATE A NEW OBJECT (a list) but it will clear and fill the existing one, like:

public void getClients(List<Client>clients){
clients.clear();
...
while(cursor.moveToNext())
clients.add(new Client(...));
...
return;
}

And the other one pattern is:

...
 private List<Client> clients;
...
// the fillinng method:
fillClients(){
   clients = dbHelper.getClients();
}

So the corresponding method gonna CREATE A NEW OBJECT (a list):

public List<Client> getClients(){
 List<Client>clients = new ArrayList<Client> clients;
...
while(cursor.moveToNext())
clients.add(new Client(...));
...
return clients;
}

The question is related to a fact that a new object creating is a valuable operation.

Roman C
  • 49,761
  • 33
  • 66
  • 176
Stan
  • 6,511
  • 8
  • 55
  • 87

1 Answers1

0

Actually I'll be careful reusing the same ArrayList. Because array behind the Arraylist would not be re-sized when we call clear().

Clear can be useful when you work with big number of elements, not creating a new object you are avoiding costs for array copy. In other cases just create a new object.

Al1en313
  • 151
  • 6