I have written a class ImmutableList<T>
which is similar to ArrayList<T>
except it does not have any add or remove operations.
Now let's say we have a class Animal
and a subclass Cat
.
I am aware that a cast from List<Cat>
to List<Animal>
is not safe, because it would allow one to insert a Dog
object into a list of cats.
This problem does not exist with immutable lists, because one cannot insert anything into an immutable list anyway:
ImmutableList<Cat> cats = ImmutableList.of(berlioz, marie, toulouse);
ImmutableList<Animal> animals = cats;
is safe, but the compiler won't allow it.
Therefore I would like to add a method to ImmutableList
that helps me to perform a safe cast, maybe like this
ImmutableList<Cat> cats = ImmutableList.of(berlioz, marie, toulouse);
ImmutableList<Animal> animals = cats.upcast();
or even
ImmutableList<Cat> cats = ImmutableList.of(berlioz, marie, toulouse);
ImmutableList<Animal> animals = cats.upcast(Animal.class);
I have tried
public <S super T> ImmutableList<S> upcast() {
return (ImmutableList) this;
}
but that does not compile (you cannot say <S super T>
here, only <S extends T>
).
The desired method should satisfy some requirements
1. It must not allow unsafe casts, such as from ImmutableList<Animal>
to ImmutableList<Cat>
2. It must be efficient, i.e. not copy the list
3. preferably not use reflection
Is it possible to write such a method? Failing that, how would you address the problem?