Re: Fwd: How to cast generic collections..

Endre Stølsvik <[email protected]> Mon, 1 Sep 2008 14:48:20 +0200
Newsgroups gmane.comp.windows.devel.java.advanced
Message-ID <[email protected]>
On Fri, Aug 29, 2008 at 6:15 PM, kevin bourrillion <[email protected]> wrote:

Thanks for answering!

>
> Your helper methods need to accept "Collection<? extends Helped>".  Then you
> should be fine, and you don't even need to cast.

Hmm.. Maybe my simplified example was too simplified or convoluted.

Since the user-facing interface DiskResource does not extend Helped,
how would the suggested solution "match"? It is the internal
DiskResourceImpl that implements Helped (and obviously DiskResource).
What I need to be able to state, is what I do in the singular case:
tell the compiler that I know something it doesn't know: This
Collection of objects, which seemingly does not implement Helped by
any route, will actually in the correct use-cases implement it anyway.
This, in the singular case, translates to "cast".

I actually thought this was somewhat commonplace in e.g. containers:
The container knows that the API-supplied user-facing Context in
question is actually an InternalContextThingy implementing lots of
internal interfaces, and casts it to what it needs when the user
supplies it as argument to the API methods. How does it cast a
user-supplied Collection of them? Is the only properish answer "one by
one"? I guess one would need a "I promise I'll only read from it!"
collection-cast. I went looking for some solution in the
Collections.unmodifiableCollection, but couldn't find any..

PS: here's another "solution" that works, possibly even more absurd
than the other two. However, we now at least avoid going all the way
down to raw types, thus giving me just the one warning which is the
same as the singular one: unchecked cast. I don't quite get why this
should be that much better than the direct cast, though..!

releaseDiskResources(Collection<DiskResorce> diskResources) {
 helper.doInternalStuff((Collection<Helped>) (Collection<?>) c);
}

Kind regards,
Endre.

===================================
This list is hosted by DevelopMentor®  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com