为什么可比较的接口被新的操作员初始化?虽然是接口?

问题描述 投票:0回答:1

下面是该类,在此,我正在使用Comparable接口。尽管它是接口,但如何使用new进行初始化?

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();
    }
}

在上面的代码中,可比较数组使用new运算符进行初始化。这怎么可能?

java string java-8 comparator comparable
1个回答
0
投票

new Comparable[capacity]不是Comparable接口的初始化,而是可以保存Comparable类型的对象的数组。您可以参考following section of JLS

© www.soinside.com 2019 - 2024. All rights reserved.