casting Collection<SomeClass> to Collection<SomeSuperClass>

Posted by skrebbel on Stack Overflow See other posts from Stack Overflow or by skrebbel
Published on 2010-03-17T09:14:47Z Indexed on 2010/03/17 9:31 UTC
Read the original article Hit count: 351

Filed under:
|
|

Hi all,

I'm sure this has been answered before, but I really cannot find it.

I have a java class SomeClass and an abstract class SomeSuperClass. SomeClass extends SomeSuperClass.

Another abstract method has a method that returns a Collection<SomeSuperClass>. In an implementation class, I have a Collection<SomeClass> myCollection

I understand that I cannot just return myCollection, because Collection<SomeClass> does not inherit from Collection<SomeSuperClass>. Nevertheless, I know that everything in myCollection is a SomeSuperClass because after all, they're SomeClass objects which extend SomeSuperClass.

How can I make this work?

I.e. I want

public class A
{
  private Collection<SomeClass> myCollection;

  public Collection<SomeSuperClass> getCollection()
  {
    return myCollection; //compile error!
  }
}

The only way I've found is casting via a non-generic type and getting unchecked warnings and whatnot. There must be a more elegant way, though? I feel that also using Collections.checkedSet() and friends are not needed, since it is statically certain that the returned collection only contains SomeClass objects (this would not be the case when downcasting instead of upcasting, but that's not what I'm doing). What am I missing?

Thanks!

© Stack Overflow or respective owner

Related posts about java

Related posts about generics