Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何向上投射不可变列表_Java_Casting_Immutablelist - Fatal编程技术网

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;
 }