Forum Stats

  • 3,760,198 Users
  • 2,251,663 Discussions
  • 7,871,021 Comments

Discussions

collection/iterator of inner class as return type of method in outer class

843793
843793 Member Posts: 41,732 Green Ribbon
edited Mar 29, 2010 5:09AM in Generics
Hello. I am not sure whether this can be done or not. If so, I cannot figure out how. I have a family of classes and I would like there to be a uniform way for an instance of any member of the family to show its contents to a caller. I would also like the caller to be able to treat each member individually rather than treating them all as one superclass.
Something like this:
class X1
{
   ...
   class Y1 {...}
   ...
   Collection<Y1> getStuffAllAtOnce() {...}
   Iterator<Y1> getStuffOneByOne() {...}
   ...
}
class X2 extends X1
{
   ...
   class Y2 extends Y1 {...}
   ...
   Collection<Y2> getStuffAllAtOnce() {...}
   Iterator<Y2> getStuffOneByOne() {...}
   ...
}
When I write it like this I get compilation errors. I understand that Collection<Y2> is not a subclass of Collection<Y1> but supposedly it will be treated as such if the compiler is satisfied that the collection will not be modified. But how does the compiler decide and how can it be convinced? Thanks. Eli

Comments

  • EJP
    EJP Member Posts: 32,920 Gold Crown
    but supposedly it will be treated as such if the compiler is satisfied that the collection will not be modified.
    Eh? Where did that come from?
  • 843793
    843793 Member Posts: 41,732 Green Ribbon
    eli_damon wrote:
    When I write it like this I get compilation errors.
    Right.
    I understand that Collection<Y2> is not a subclass of Collection<Y1>
    Also correct, but irrelevant; Collection<Y2> would need to be a subtype of Collection<Y1>.
    but supposedly it will be treated as such if the compiler is satisfied that the collection will not be modified. But how does the compiler decide and how can it be convinced?
    Well, the subtype relationship would be sound if the collection could not be modified, however Java has no concept of such immutability and thus the compiler can't verify it. What you can do is use an upper-bounded wildcard; Collection<? extends Y1> is a supertype of Collection<? extends Y2>.

    With kind regards
    Ben
  • 843793
    843793 Member Posts: 41,732 Green Ribbon
    I figured it out. I works if I do this.
    class X1
    {
       ...
       class Y1 {...}
       ...
       Collection<? extends Y1> getStuffAllAtOnce() {...}
       Iterator<? extends Y1> getStuffOneByOne() {...}
       ...
    }
    class X2 extends X1
    {
       ...
       class Y2 extends Y1 {...}
       ...
       Collection<? extends Y2> getStuffAllAtOnce() {...}
       Iterator<? extends Y2> getStuffOneByOne() {...}
       ...
    }
This discussion has been closed.