Java 如何向上投射不可变列表
我编写了一个类Java 如何向上投射不可变列表,java,casting,immutablelist,Java,Casting,Immutablelist,我编写了一个类ImmutableList,它类似于ArrayList,只是它没有任何添加或删除操作 现在让我们假设我们有一个类Animal和一个子类Cat 我知道从列表到列表的转换是不安全的,因为这样可以将狗对象插入猫的列表中 不可变列表不存在此问题,因为无法在不可变列表中插入任何内容: ImmutableList<Cat> cats = ImmutableList.of(berlioz, marie, toulouse); ImmutableList<Animal> a
ImmutableList
,它类似于ArrayList
,只是它没有任何添加或删除操作
现在让我们假设我们有一个类Animal
和一个子类Cat
我知道从列表
到列表
的转换是不安全的,因为这样可以将狗
对象插入猫的列表中
不可变列表不存在此问题,因为无法在不可变列表中插入任何内容:
ImmutableList<Cat> cats = ImmutableList.of(berlioz, marie, toulouse);
ImmutableList<Animal> animals = cats;
甚至
ImmutableList<Cat> cats = ImmutableList.of(berlioz, marie, toulouse);
ImmutableList<Animal> animals = cats.upcast(Animal.class);
ImmutableList猫=ImmutableList.of(柏辽兹、玛丽、图卢兹);
ImmutableList动物=cats.upcast(Animal.class);
我试过了
public <S super T> ImmutableList<S> upcast() {
return (ImmutableList) this;
}
public不可变列表上传(){
返回(不可变列表)此项;
}
但这并不能编译(这里不能说
,只能说
)
所需的方法应满足某些要求
1.它不能允许不安全的强制转换,例如从ImmutableList
到ImmutableList
2.必须有效,即不复制列表
3.最好不要使用反射
有可能写出这样一种方法吗?如果做不到这一点,你将如何解决这个问题 为什么不直接使用ImmutableList@JBNizet当前位置由于以下原因,我不愿意这样做。然后我必须使用ImmutableList
public <S super T> ImmutableList<S> upcast() {
return (ImmutableList) this;
}