Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics error: Cannot convert from E to E?

Tags:

java

generics

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'm getting a compilation error that says that I can't convert my input file, which is of type E, into type E. Why is this? Is it because It's not technically the same type E?

like image 771
iii Avatar asked Dec 01 '25 21:12

iii


2 Answers

Yout are declaring two type parameters with the same name E. There is no need to do that. The type parameter in the class declaration PriorityQueue<E> is enough.

Change

public <E> int insert(E input)

to

public int insert(E input)
like image 110
Eran Avatar answered Dec 04 '25 11:12

Eran


Remove the generic parameter from your insert method and it will compile. You do not need to be generic at the method level because you already have the type of your queue in the generic parameter of the class.

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;
    }
}
like image 30
Marcel Baumann Avatar answered Dec 04 '25 09:12

Marcel Baumann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!