1

My code is as below:

private <A extends AbstractDocument> List<A> reorderDocuments(List<A> docs)
    {
        List<A> newdoclist = new ArrayList<A>();
        for (A o : docs) {
            if(//some condition) {
                //TODO::Generic type
                List<A> tempDocs = new ArrayList<A>();
                tempDocs.add( o );
                tempDocs.addAll(o.getAlikeDocuments());
                //sort method called
            } 
          return newdoclist;
    }

have changed the start tag for the type with the function o.getAlikeDocuments() returns List of type Abstract document, but this method is still giving me error on line tempDocs.addAll(o.getAlikeDocuments()); saying The method addAll(Collection<? extends A>) in the type List is not applicable for the arguments (List<AbstractDocument>). Appreciate the help in advance.

Thanks

Vaibhav

vaibhav
  • 3,929
  • 8
  • 45
  • 81

2 Answers2

3

The problem you have is that A is a subclass of AbstractDocument and you may not add any AbstractDocument except sub-classes of A

To make it compile, if you know this is not a problem is to use type erasure.

 tempDocs.addAll((List) o.getAlikeDocuments());
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Only if he's sure that o.getAlikeDocuments() will definitely return a List of objects of type A (or sub-type). It looks like the return type of this method is List which means, if he uses your solution, he could end up adding AbstractDocument objects to a List. – CodeClimber Mar 31 '11 at 09:37
  • 1
    just noticed you did say "if you know this is not a problem" – CodeClimber Mar 31 '11 at 09:37
  • Yeah it makes sense for me cos the return type of this method would always be AbstractDocument, Thanks for the help! appreciate it! – vaibhav Mar 31 '11 at 09:41
  • But only if you're sure, at runtime, that the objects returned by o.getAlikeDocuments() will be of type A (or a sub-type). If they are of type AbstractDocument then the code that calls reorderDocuments() can end up with a List that contains an AbstractDocument object which could cause all kinds of problems. – CodeClimber Mar 31 '11 at 10:17
  • In which case the method should return a List ;) – Peter Lawrey Mar 31 '11 at 10:20
0

Casting to a raw list will do the trick

tempDocs.addAll((List) o.getAlikeDocuments());

The following page might help to memorize the restrictions of extends and super

What is PECS (Producer Extends Consumer Super)?

Community
  • 1
  • 1
Timo Westkämper
  • 21,824
  • 5
  • 78
  • 111