aspose file tools*
The moose likes Java in General and the fly likes Generics question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Generics question" Watch "Generics question" New topic
Author

Generics question

D. Ogranos
Ranch Hand

Joined: Feb 02, 2009
Posts: 214
In my current project, I'm trying to do something like this:



Each ExtendedClass has its own ExtendedType class. Each ExtendedClass so far has its own method getTypes() which returns a Set<ExtendedType> which is then used further. Now what I want to do is refactor this so that getTypes() is in BaseClass. However I don't think there's a way to create a correctly typed set in the BaseClass and return it (or is there?), so I want to pass the set to the setTypes() method instead which should fill it then.

But when compiling, the above code produces the error "setTypes(Set<? super BaseType>) in BaseClass cannot be applied to (Set<ExtendedType>)". I'm not sure what I'm doing wrong here...any help appreciated.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4364
    
    8

You're calling setTypes(Set<ExtendedType>)

That doesn't work because ExtendedType is not a super-class of BaseType, it's a subclass. It would work if you used ? extends BaseType (but of course you wouldn't be able to add to the set then).
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19670
    
  18

Make BaseClass generic:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
D. Ogranos
Ranch Hand

Joined: Feb 02, 2009
Posts: 214
Thanks for the answers, going to give the above suggestion a try! Not too experienced with writing such generic classes but I guess it makes sense here.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Generics question