0

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.

LatinCanuck
  • 454
  • 2
  • 10
  • 29
  • `List extends Fruit>` can accept `List` or `List`. Do you think compiler should let you add potential Bananas to potential list of Apples? – Pshemo Jan 27 '14 at 20:59

3 Answers3

2

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.

Community
  • 1
  • 1
Marco13
  • 53,703
  • 9
  • 80
  • 159
1

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.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Thrash Bean
  • 658
  • 4
  • 7
0

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);
}
Spindizzy
  • 7,244
  • 1
  • 19
  • 33