Nathan Lyon
Nathan Lyon

Reputation: 11

How do I resolve the incompatible types in my code

I have to implement my own ArrayList class using generics for a java assignment. For some reason I'm getting an incompatible type error and I have failed in my attempt to find help elsewhere.

Here is my code followed by the exact error:

public <E> boolean addItem ( E item ) 
{           
    if ( numElements == list.length ) {             
        enlarge();
        list [numElements] = item;
        numElements ++;
        return true;
    } else {                
        list [numElements] = item;
        numElements ++;
        return true;
    }
}

the Error:

ArrayList.java:91: error: incompatible types
                        list [numElements] = item;
                                             ^(points at item)
  required: E#2
  found:    E#1
  where E#1,E#2 are type-variables:
    E#1 extends Object declared in method <E#1>addItem(E#1)
    E#2 extends hasKey declared in class ArrayList

I apologize if this has been answered elsewhere, I'm just not sure what I should be searching for to find the answer I need.

Upvotes: 1

Views: 158

Answers (1)

Eran
Eran

Reputation: 394126

Based on your error you have two type variables called E, one in the class level and one in the method addItem. You should simply remove the type parameter from the addItem method.

Change

public <E> boolean addItem (E item)

to

public boolean addItem (E item)

The same applies to any other non-static methods of your class having a generic type parameter which represents the ArrayList member type. They should all use the generic type parameter declared in the class level.

Upvotes: 4

Related Questions