我写了一个ImmutableList<T>类似于的类,ArrayList<T>除了它没有任何添加或删除操作。
现在假设我们有一个类Animal和一个子类Cat。
我知道从List<Cat>to 转换List<Animal>是不安全的,因为它允许将Dog对象插入到猫列表中。
不可变列表不存在此问题,因为无论如何都无法将任何内容插入不可变列表:
ImmutableList<Cat> cats = ImmutableList.of(berlioz, marie, toulouse);
ImmutableList<Animal> animals = cats;
是安全的,但编译器不允许这样做。
因此,我想添加一个方法来ImmutableList帮助我执行安全演员,也许像这样
ImmutableList<Cat> cats = ImmutableList.of(berlioz, marie, toulouse);
ImmutableList<Animal> animals = cats.upcast();
甚至
ImmutableList<Cat> cats = ImmutableList.of(berlioz, marie, toulouse);
ImmutableList<Animal> animals = cats.upcast(Animal.class);
我努力了
public <S super T> ImmutableList<S> upcast() {
return (ImmutableList) this;
}
但这不会编译(你不能<S super T>在这里说,只有<S extends T>)。
所需的方法应满足一些要求
1. 不能允许不安全的强制转换,例如 from ImmutableList<Animal>to ImmutableList<Cat>
2. 必须高效,即不复制列表
3. 最好不要使用反射
有可能写出这样的方法吗?如果做不到这一点,您将如何解决问题?