添加到此隊列時,我一直收到一個空指針異常,特別是滲透物向上。我認爲我的設置有些問題,但我無法弄清楚。當我嘗試添加東西時出現錯誤,並且我的IDE說它的空指針異常和比較方法中存在問題,這讓我認爲compare方法中的if else語句指向一個空值。我無法弄清楚他們爲什麼會這樣做?這個優先級隊列邏輯java有什麼問題?
public class GenericHeap<E> {
int size;
int capacity = 10;
public E[] heap;
Comparator mycomparator;
public GenericHeap(Comparator c) {
heap = (E[]) new Object[capacity];
mycomparator = c;
}
public void add(E e) {
if (size == 0) {
heap[size++] = e;
} else {
heap[size++] = e;
this.percolateup(this.size);
}
}
private void percolateup(int I) {
E temp;
while (I/2 > 0) {
if (mycomparator.compare(heap[I/2], heap[I]) == 1) {
temp = heap[I/2];
heap[I/2] = heap[I];
heap[I] = temp;
}
I = I/2;
}
}
public int compare(String t, String t1) {
if (t.length()>t1.length()){
return 1;}
else if (t.length()<t1.length()){
return -1;}
return t.compareTo(t1);
}}
那麼,你有沒有在調試器中加入代碼?那是第一步。 – OldProgrammer
你能提供堆棧跟蹤嗎? –
好像你正在將一個沒有實例化的對象添加到隊列中。確保要添加到隊列中的對象已實例化並具有有效的引用。另外,你還沒有在這裏給出完整的代碼。隊列在哪裏? – ha9u63ar