mercredi 19 mai 2021

Update a list reference inside a method

In Java we can not reassign a reference inside a method.
So the following does not work:

class SomeClass {  
  
  public void process(List<OrderStatus> data, List<Orders> currentOrderlist) {
     List<Person> newOrders = fromOrderStatus(data);  
     currentOrderlist = newOrders;  
  } 
}

But the following does work:

class SomeClass {  
  
  public void process(List<OrderStatus> data, List<Orders> currentOrderlist) {
     List<Person> newOrders = fromOrderStatus(data);  
     currentOrderlist.clear();  
     currentOrderlist.addAll(newOrders); // <- extra linear loop  
  } 
}

The problem is that the second example does an extra linear loop to copy from one list to the other.

Question:
I was wondering, is there some design approach so that I could neatly just replace the references instead? I.e. somehow make the first snippet work with some change in the parameters or something?

Aucun commentaire:

Enregistrer un commentaire