Search code examples
javagenericsarraylistheappriority-queue

cannot find symbol / cannot convert object to comparable using ArrayList in generics


In this program, I am creating a heap priority queue using arraylists in Java. I'll try to keep the code bare to help in resolving the issue easier.

Essentially, I have define an interface for the heapAPI and implement it in the Heap class. The Heap constructor is supposed to construct the heap object by defining an arraylist of objects. Here, I want to pass objects of the PCB class (jobs to go into the priority queue). However, when I pass these objects, I'm unable to access them through the arraylist.

Attached below is the code for the HeapAPI, Heap class, and PCB class.

HeapAPI.java

public interface HeapAPI<E extends Comparable<E>>
{
     boolean isEmpty();
     void insert(E item);
     E remove() throws HeapException;
     E peek() throws HeapException;
     int size();
}

Heap.java

public class Heap<E extends Comparable<E>> implements HeapAPI<E>
{
     private ArrayList<E> tree;

     public Heap()
     {
          tree = new ArrayList<>();
     }

// don't believe the rest of the class is necessary to show
}

PCB.java

public class PCB implements Comparable<PCB>
{
     private int priority;

     // various private variables

     public PCB()
     {
       priority = 19;
       // instantiated variables
     }

    // don't believe the rest of the code is necessary
    // the one specific function of PCB I use follows

     public int getPriority()
     {
          return priority;
     }
}

I have tried the following main method to call functions of PCB object through the ArrayList after inserting the PCB objects into an arraylist of Heap object.

Main.java

public class Main 
{
     public static void main(String[] args) throws HeapException
     {
          Heap temp = new Heap();
          PCB block = new PCB();
          PCB block1 = new PCB();
          PCB block2 = new PCB();

          temp.insert(block);
          temp.insert(block1);
          temp.insert(block2);

          block.getPriority();

          // does not work
          int num = temp.peek().getPriority();
          //does not work
          num = temp.get(0).getPriority();
}

The error I am getting that the program cannot find the symbol: method getPriority().

[Also, import java.util.ArrayList; is called in each file]

I've been attempting to learn and apply generics for a hot minute, but I'm just stuck now.

If I was not clear on anything, I can easily add more code or clarify the issue.

Any assistance is appreciated.

Thanks!


Solution

  • Here's the problem:

    Heap temp = new Heap();
    

    You have a generic Heap class but here you are creating it without its generics. This is an example of Raw Types.

    Something like:

    Heap<PCB> temp = new Heap<>();
    

    should work.