Can't convert ArrayList<subtype> to ArrayList<type>

arraylist, java, type-conversion

Solution

You need to use:

public interface Layer
{
    public ArrayList<? extends Neuron> getNeurons();
}

because of lack of covariance and contravariance in generics. If you return an ArrayList < INeuron > as an ArrayList < Neuron > then you would potentially be able to add an element that is not a INeuron (like another child of Neuron) to an ArrayList < INeuron >

Problem

I'm writing a program to simulate an artificial neural network. I have the following classes and interfaces set up: ``` 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 } ``` The compiler reports "cannot convert from ArrayList<INeuron> to ArrayList<Neuron>." I've tried switching things around. For example: `ArrayList<Neuron> neurons = new ArrayList<INeuron>()`. But that just seems to shift the same error to different parts of the class. I don't understand why INeuron can't be implicitly cast to Neuron since INeuron is a subtype of Neuron.

Original source