Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add generic items to a generic ArrayList?

I have an assignment which requires me to implement a generic priority queue from scratch, however I'm getting an error that I don't think makes any sense.

public class PriorityQueue<E> {
     private ArrayList<E> items = new ArrayList<E>(0);
     ...
     public <E extends Comparable<E>> void insert(E newItem){

       if(numOfItems == 0){
          items.add(newItem); //ERROR: The method add(E) in the type ArrayList<E> 
                                       is not applicable for the arguments (E)
          rear++;
          numOfItems++;
       }else{
            //INCOMPLETE
       }
    }
}
like image 551
user3094042 Avatar asked Dec 12 '13 07:12

user3094042


People also ask

How do you add an element to a generic list in Java?

Accessing a Generic List. You can get and insert the elements of a generic List like this: List<String> list = new ArrayList<String>; String string1 = "a string"; list. add(string1); String string2 = list.


1 Answers

public <T extends Comparable<E>> void insert(E newItem){

Change the first 'E' to 'T', since the type parameter is hiding the original 'E'

like image 182
aquaraga Avatar answered Sep 30 '22 17:09

aquaraga