Fwd: How to cast generic collections..

Endre Stølsvik <[email protected]> Fri, 29 Aug 2008 14:58:28 +0200
Newsgroups gmane.comp.windows.devel.java.advanced
Message-ID <[email protected]>
Hi.

I have bumped into a problem a couple of times which I can't seem to
quite understand how to handle best. It revolves around casting the
type of a generic collection.

My situation is something like this: An interface DiskResource, whose
instances users get from a DiskProvider extends Provider instance.

The DiskProvider has these two methods:
releaseDiskResource(DiskResource diskResource);
releaseDiskResources(Collection<DiskResource> diskResources);

I have this helper class for implementing Providers, called Helper.
This helper requires that the Resources implement Helped. I therefore
make a DiskResourceImpl which implement DiskResource and Helped. I
thus need to implement the DiskProviderImpl as such:

releaseDiskResource(DiskResource diskResource) {
  // Cast, with unchecked-warning:
  helper.doInternalStuff((Helped) diskResource)
}

releaseDiskResources(Collection<DiskResorce> diskResources) {
  // PROBLEM HERE, this cast is an ERROR, not a warning:
  helper.doInternalStuff((Collection<Helped>) resourceImpls);
}

How am I supposed to do this cast? See, I know why it isn't allowed to
cast like that, but I want to nevertheless! It seems strangely
non-symmetric that I just cast it in the singular version (with a
unchecked-warning), but end up with an error in the other. Is the
latter that more dangerous than the first?

Both these are "solutions":
releaseDiskResources(Collection<DiskResorce> diskResources) {
  Collectioc<Helped> c = new HashSet<Helped>();
  for(DiskResource diskResource : diskResources) {
    c.add((Helped) diskResource);
  }
  helper.doInternalStuff(c);
}

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

.. of which I refuse to use #1, while #2 seems like a just-to-weird
hack around the compiler error, replacing the error with two warnings
(!). Raw types are the evilest there is, are they not?

I hope this example points out my annoyance while not being too convoluted.

Where is my thinking derailing? I have a feeling it is a couple of
steps before these methods' implementation, but I've tried different
attacks now. I don't want the users of this API to see internal stuff
that is useless for them.

Regards.
Endre.

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

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