I have the following method:
private void updateEntries(List<Data> data, List<Order> orders) {
// processing code here
List<Order> updates = new ArrayList<>();
for(Data d: data) {
Order anOrder = createOrder(d);
if(anOrder != null) {
updates.add(anOrder);
}
}
orders.clear();
orders.addAll(updates);
}
The method createOrder
will create a subtype of Order
based on the Data
argument. This part compiles.
But the problem is that the calling code of the method will not compile since it is called as follows:
updateEntries(List<Data> data, List<PendingOrder> orders)
and
updateEntries(List<Data> data, List<ExecutedOrder> orders)
both of these are subtypes of Order
and hence the code won't compile on the calling side of the method.
If I update the code as follows:
private void updateEntries(List<Data> data, List<? extends Order> orders) {
// processing code here
List<Order> updates = new ArrayList<>();
for(Data d: data) {
Order anOrder = createOrder(d);
if(anOrder != null) {
updates.add(anOrder);
}
}
orders.clear();
orders.addAll(updates); // <= does not compile
}
The problem is with the line: orders.addAll(updates);
That does not compile of course because the list is declared as List<? extends T>
and it tries to avoid adding items of different types in the list.
So how can I use generics so I reuse the function and be able to update the list in the method?