Reputation: 463
So I have this situation. I've been given the task of adding the contents of one list to another list. Sounds simple enough. My problem is this, the existing list has the following syntax :
// Existing code
List<? extends ProductCatalog> listProduct = null;
listProduct = RetrieveService.getInstance().getListProduct("client1");
// My code is
List<? extends ProductCatalog> listProduct2 = null;
listProduct2 = RetrieveService.getInstance().getListProduct("client2");
If listProduct was a normal List, I'd just use AddAll. But it doesn't work with extend. Or most probably, I'm doing it wrong. So in this example, how would I add listProduct2 to listProduct.
Any help would be appreciated.
Upvotes: 0
Views: 124
Reputation: 8924
Can you avoid the extends keyword in the generics and use <ProductCatalog>
only? That could make you life easier.
However, generics are a compile time construct. So you could write a method that has the two lists as arguments without generics. This way you can put anything in the list. But it is not a clean way and may cause some other problems especially if you have a source code quality check;-)
add(clientProduct, clientProduct2);
private void add(List clientProduct, List clientProduct2){
clientProduct.addAll(clientProduct2);
}
Upvotes: 0
Reputation: 658
If is mandatory the use of <? extends ProductCatalog>
will be difficult, but if you can implement an empty interface in your class ProductCatalog and then declare List<your_interface> listProduct
it could work.
Upvotes: 1
Reputation: 54639
It's not possible in a type-safe way. Also see e.g. How can I add to List<? extends Number> data structures?
You might combine them both in a new List<ProductCatalog>
, depending on the goal that you want to achieve.
Upvotes: 2