Read-only view of a Java list with more general type parameter
Posted
by Michael Rusch
on Stack Overflow
See other posts from Stack Overflow
or by Michael Rusch
Published on 2010-04-08T17:22:56Z
Indexed on
2010/04/08
17:33 UTC
Read the original article
Hit count: 455
Suppose I have class Foo extends Superclass. I understand why I can't do this:
List<Foo> fooList = getFooList();
List<Superclass> supList = fooList;
But, it would seem reasonable for me to do that if supList were somehow "read-only". Then, everything would be consistent as everything that would come out of an objList would be a Foo, which is a Superclass.
I could probably write a List implementation that would take an underlying list and a more general type parameter, and would then return everything as the more general type instead of the specific type. It would work like the return of Collections.unmodifiableList()
except that the type would be made more general.
Is there an easier way?
The reason I'm considering doing this is that I am implementing an interface that requires that I return an (unmodifiable) List<Superclass>, but internally I need to use Foos, so I have a List<Foo>. I can't just cast.
© Stack Overflow or respective owner