Java Generics error: Can't convert from E to E?

public class PriorityQueue<E> {


private E[] array;
private int size;
private int front;
private int back;
private int numOfElements = 0;
private static int EMPTY = 0;



public <E> int insert(E input)
{
    if (numOfElements + 1 <= size)
    {
        array[back] =  input;
        back++;
        numOfElements++;

    }


    return 0;
}

      

For some reason, I am getting a compilation error that says I cannot convert my input file, which is of type E, to type E. Why is this? Is it because it's not technically the same type E?

+3


source to share


2 answers


Yout declares two types of parameters with the same name E

. You don't need to do this. The type parameter in the class declaration is PriorityQueue<E>

sufficient.

Edit

public <E> int insert(E input)

      



to

public int insert(E input)

      

+9


source


Extract the shared parameter from the insert method and compile it. You don't need to be generic at the method level because you already have the type of your queue in the generic class parameter.



public class PriorityQueue<E> {


    private E[] array;
    private int size;
    private int front;
    private int back;
    private int numOfElements = 0;
    private static int EMPTY = 0;


    public int insert(E input) {
        if (numOfElements + 1 <= size) {
            array[back] = input;
            back++;
            numOfElements++;

        }
        return 0;
    }
}

      

+3


source







All Articles