24

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!

skrebbel
  • 9,841
  • 6
  • 35
  • 34

11 Answers11

23

Will Collection<? extends SomeSuperClass> not do what you want?

ishmeister
  • 599
  • 1
  • 3
  • 8
  • 3
    This is the correct way to go about this. See: http://java.sun.com/docs/books/tutorial/extra/generics/wildcards.html – Adam Jul 01 '10 at 15:21
  • 1
    Beware when using in an API: "Do not use wildcard types as return types. Rather than providing additional flexibility for your users, it would force them to use wildcard types in client code." Effective Java Item 28 https://stackoverflow.com/a/22815270/774398 – Patrick May 26 '17 at 11:46
11

You can't do this. You have a Collection<SomeClass> and wish to return a Collection<SuperClass>

Now imagine that someone has your returned Collection - and they try to insert a different subclass of SuperClass, SomeOtherClass. This should be allowed on your SuperClass collection - but it can't because it's actually a Collection<SomeClass>, unbeknownst to anyone but the private member of A.

Steven Schlansker
  • 37,580
  • 14
  • 81
  • 100
  • Aha! Thanks :-) Sounds like I need an immutable view. – skrebbel Mar 17 '10 at 09:23
  • Hmm is there standard library support for immutable views? :-) – skrebbel Mar 17 '10 at 09:26
  • Why is 'my solution' possible? Am I missing something (see my Answer below) – Stefan Hendriks Mar 17 '10 at 09:39
  • -1 you can do this. See ishmeister's answer below using wildcards. – Adam Jul 01 '10 at 15:23
  • 6
    Java has support for unmodifiable views in [Collections](http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#unmodifiableCollection(java.util.Collection)). The `unmodifiable` methods also take type parameters and allow it to return a collection of a superclass type. `public static Collection unmodifiableCollection(Collection extends T> c)` – Jake Walsh Mar 25 '14 at 23:01
7

Java 8 now offers a neater way of doing it using lambdas: you can use the map() and collect() functions to cast the objects to your super class. A solution for your example would look like this:

public class A
{
    private Collection<SomeClass> myCollection;

    public Collection<SomeSuperClass> getCollection()
    {
        return myCollection.stream().map(x -> (SomeSuperClass) x).collect(Collectors.toList());
    }
}

You can also use other Collectors if needed.

Vlad Schnakovszki
  • 8,434
  • 6
  • 80
  • 114
1

If you create a new collection of the correct type you can populate it using the old collection

public Collection<SomeSuperClass> getCollection()
{
    return new ArrayList<SomeSuperClass>(myCollection); 
}
Konstantin
  • 3,626
  • 2
  • 33
  • 45
1

Based on the top answer given to this question: How do you cast a List of supertypes to a List of subtypes?

I do believe it is possible to do

Collection<SomeSuperType> variable =
                    (Collection<SomeSuperType>)(Collection<?>) collectionOfSomeType;

At the expense of an "unchecked" warning. At the linked question, concern has been expressed about the "hackiness" of this answer due to the lack of type safety. However, in this question's context (namely casting a collection of subtypes to a collection of their supertypes) I see no problems or possible ClassCastExceptions. And in any case, it works quite well.

Community
  • 1
  • 1
Davi
  • 11
  • 2
0

I am not sure why; perhaps someone else can explain this; but it works if you do:

public abstract class SomeSuperClass<E> {
    abstract public Collection<SomeSuperClass<E>> getCollection();
}

and:

public class Someclass extends SomeSuperClass {
    @Override
    public Collection<Someclass> getCollection() {
        // TODO Auto-generated method stub
        return null;
    }
}
Stefan Hendriks
  • 4,705
  • 5
  • 34
  • 43
  • I'd be very interested in that too. Sure you're not getting any unchecked warnings somehow? Either way, you're extending a generic class without making the subclass generic, that sounds like a weird thing to start with.. – skrebbel Mar 17 '10 at 09:48
  • Yes it is strange. If you do make the subclass more concrete you get: public class Someclass extends SomeSuperClass { @Override public Collection> getCollection() { // TODO Auto-generated method stub return null; } } I have never used such a construction before, it does not really look like a good way to me. – Stefan Hendriks Mar 17 '10 at 11:41
  • Your Someclass extends SomeSuperClass, which is a raw type because SomeSuperClass is declared as . I believe that since you extend a raw type, you'll get a warning for that but then not get further unchecked warnings on the individual methods even though they are actually unchecked conversions. – Steven Schlansker Mar 17 '10 at 18:12
0

perhaps, you should do some workaround.

for example, you should make some "HolderClass" with generic extension, and then you'll be able to put weather your SomeClass, weather your SomeSuperClass.

take a look:

public class HolderClass<E extends SomeSuperClass> {

    private final Collection<E> myClass;

    public HolderClass() {
        myClass = new ArrayList<E>();
    }

    public void putSomeClass(final E clazz) {
        myClass.add(clazz);
    }

    public Collection<E> getMyClasses() {
        return myClass;
    }

} 

and you can make collection this way:

HolderClass<SomeSuperClass> holderClass = new HolderClass<SomeSuperClass>();
holderClass.putSomeClass(new SomeClass());
holderClass.putSomeClass(new SomeSuperClass());

and now, when you make call to getMyClasses(), you'll get collection of SomeSuperClasses

0

Yes we can!

class A {@Override
public String toString()
{

  return "A";
} };
class B extends A {
  @Override
  public String toString()
  {      
    return "B";
  }
};
List<A> l1 = new ArrayList<A>();
l1.add(new A());
List<B> l2 = null;
l2 = (List<B>)(List<? extends A>)l1;
l2.add(new B());

System.out.println( Arrays.toString( l2.toArray() ) );

please test it

Adam111p
  • 3,469
  • 1
  • 23
  • 18
0

Here is a complete solution.

Use of the following static method saves you from warnings about unchecked casts. The seemingly superfluous assignment to result before returning result is actually necessary in order to be able to use @SuppressWarnings.

/**
 * Casts a {@link Collection} to a {@link Collection} of an ancestral element type.
 *
 * @param collection the {@link Collection} to down-cast.
 * @param <T>        the required ancestral element type.
 *
 * @return the same {@link Collection} where the element type is the given ancestral type.
 */
public static <T> Collection<T> downCast( Collection<? extends T> collection )
{
    @SuppressWarnings( "unchecked" ) Collection<T> result = (Collection<T>)collection;
    return result;
}

Use it as follows:

class Ancestor {}
class Descendant extends Ancestor {} 
Collection<Descendant> descendants;
Collection<Ancestor> ancestors = downCast( descendants );

Also works with generics:

class Ancestor<T> {}
class Descendant<T> extends Ancestor<T> {} 
Collection<Descendant<T>> descendants;
Collection<Ancestor<T>> ancestors = downCast( descendants );
Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
-3

A collection of SubType is not substitutable for SuperType.

Everyone
  • 2,366
  • 2
  • 26
  • 39
  • Well, clearly I know that. My problem was that I wanted to work around that. My real problem was that I did not understand *why* a collection of SubType is not substitutable for SuperType. Answering a question that goes "I can't do X, is there a workaround" by "You can't do X" sounds like you're just trying to score stackoverflow points. – skrebbel Mar 17 '10 at 09:46
  • You might want to take a gander at http://stackoverflow.com/questions/15496/hidden-features-of-java/55221#55221 – Everyone Mar 17 '10 at 10:14
-3

.NET 4.0 introduces covariance and contravariance to generics:

http://msdn.microsoft.com/en-us/library/dd799517(VS.100).aspx

Kip
  • 335
  • 5
  • 14