Parminder Singh
Parminder Singh

Reputation: 29

Why Comparable Interface is intialise with new Operator? though it is interface?

Below is the class and in this, I'm using a Comparable interface. How can it is initialized with new, though it is an interface?

public class PriorityQueueImpl {

    @SuppressWarnings("rawtypes")
    private Comparable[] pQueue;
    private int index;

    public PriorityQueueImpl(int capacity){
        pQueue = new Comparable[capacity];
    }

    public void insert(Comparable item ){
    if(index == pQueue.length){
        System.out.println("The priority queue is full!! can not insert.");
        return;
    }
        pQueue[index] = item;
        index++;
        System.out.println("Adding element: "+item);
    }
    @SuppressWarnings("unchecked")
    public Comparable remove(){
        if(index == 0){
            System.out.println("The priority queue is empty!! can not remove.");
        return null;
        }
        int maxIndex = 0;
        // find the index of the item with the highest priority
        for (int i=1; i<index; i++) {
            if (pQueue[i].compareTo (pQueue[maxIndex]) > 0) {
                maxIndex = i;
            }
        }
        Comparable result = pQueue[maxIndex];
        System.out.println("removing: "+result);
        // move the last item into the empty slot
        index--;
        pQueue[maxIndex] = pQueue[index];
        return result;
    }

    public static void main(String a[]){
        PriorityQueueImpl pqi = new PriorityQueueImpl(5);
        pqi.insert(34);
        pqi.insert(23);
        pqi.remove();
        pqi.remove();
    }
}

in the above code, Comparable Array initializes with the new operator. how is this possible?

Upvotes: 0

Views: 67

Answers (1)

Prashant
Prashant

Reputation: 5393

new Comparable[capacity] is not an initialisation ofComparable interface but an array that can hold objects of type Comparable. You can refer following section of JLS

Upvotes: 3

Related Questions