以下代碼是合法傳遞編譯的。爲什麼可以將PriorityQueue定義爲只採用instanceof Comparable的元素?爲什麼priorityQueue在編譯時需要可比的接口?
...
PriorityQueue<Object> q = new PriorityQueue<Object>();
q.add(new Object());
...
但它引發的預期例外:
Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.Comparable
at java.util.PriorityQueue.siftUpComparable(PriorityQueue.java:595)
at java.util.PriorityQueue.siftUp(PriorityQueue.java:591)
at java.util.PriorityQueue.offer(PriorityQueue.java:291)
at java.util.PriorityQueue.add(PriorityQueue.java:268)
at ReentrantLockExample.main(ReentrantLockExample.java:12)