Bar*_*own 3 java arraylist type-conversion
我正在编写一个模拟人工神经网络的程序.我设置了以下类和接口:
public interface Neuron
{
}
// Input neuron
public class INeuron implements Neuron
{
}
// Output and hidden neuron
public class ONeuron implements Neuron
{
}
public interface Layer
{
public ArrayList<Neuron> getNeurons();
}
// Input layer
public class ILayer implements Layer
{
ArrayList<INeuron> neurons = new ArrayList<INeuron>();
public ArrayList<Neuron> getNeurons()
{
return neurons;
}
// other stuff appropriate to the input layer
}
Run Code Online (Sandbox Code Playgroud)
编译器报告"无法从ArrayList <INeuron>转换为ArrayList <Neuron>".
我试过转换东西.例如:ArrayList<Neuron> neurons = new ArrayList<INeuron>().但这似乎只是将同样的错误转移到了班级的不同部分.
我不明白为什么INeuron不能被隐含地投射到Neuron,因为INeuron是神经元的一个子类型.
你需要使用:
public interface Layer
{
public ArrayList<? extends Neuron> getNeurons();
}
Run Code Online (Sandbox Code Playgroud)
因为在仿制药中缺乏协方差和逆变.如果将ArrayList <INeuron>作为ArrayList <Neuron>返回,那么您可能能够将一个不是INeuron的元素(如Neuron的另一个子元素)添加到ArrayList <INeuron>