2011-04-18 45 views
0

對於我的數據結構類,我們的任務是實現一個使用已創建的基於數組的隊列的PriorityQueue類。除了克隆方法外,一切都在PriorityQueue類中工作。當克隆方法被激活時,即使正在克隆的隊列中有數據,也不會返回任何內容。 PriorityQueue類使用ArrayQueues數組。我只是從我的類複製構造函數和克隆方法。PriorityQueue中的clone()方法實現

感謝您的幫助

private ArrayQueue<E>[] queues; 
private int manyItems; 
private int highest; 

public PriorityQueueArray(int a_highest) { 
    manyItems = 0; 
    highest = a_highest; 
    queues = new ArrayQueue[a_highest+1]; 
    for(int i = 0; i <= a_highest; i++) { 
     queues[i] = new ArrayQueue(); 
    } 
} 

public PriorityQueueArray<E> clone() { 
    PriorityQueueArray<E> answer; 

    try{ 
     answer = (PriorityQueueArray<E>) super.clone(); 
    } catch (CloneNotSupportedException e) { 
     // This exception should not occur. But if it does, it would probably indicate a 
     // programming error that made super.clone unavailable. The most common error 
     // The most common error would be forgetting the "Implements Cloneable" 
     // clause at the start of this class. 
     throw new RuntimeException 
      ("This class does not implement Cloneable");   
    } 
    for(int i = 0; i <= highest; i++) { 
     answer.queues[i] = queues[i].clone(); 
    } 
    return answer; 
} 
+0

什麼是「什麼都沒有返回」的意思?隊列中爲空或空陣列? – 2011-04-18 00:54:57

+0

當返回一個PriorityQueueArray對象時,實例變量manyItems會從被克隆的對象(5)中返回正確的數字,但是正在克隆的PriorityQueueArray中的項目(隊列[])不會被複制到答案變量中。 – Chad 2011-04-18 01:10:17

回答

0

我認爲問題在於queues未被正確克隆。試試這個:

​​

你原來的代碼依賴於super.clone()做了很多的工作,但是該方法的默認版本做了淺克隆,而且不會使queues數組的一個副本。所以你最終得到一個與原始數據共享隊列數組的「克隆」。這將意味着ArrayQueue情況下將被分享,而奇怪的事情發生......

(假設我們需要手動newqueues陣列,它最簡單的手動複製其他2場也是如此。)

我們需要查看您的單元測試,以瞭解如何/爲什麼會導致您看到的症狀。

+0

非常感謝斯蒂芬,那是關鍵!我沒有爲這個克隆創建一個新的ArrayQueue。 – Chad 2011-04-18 01:32:40

1

嘗試使用

@Override 
public Object clone() throws CloneNotSupportedException { 
    // your method here. 
    ... 
} 

方法簽名。它看起來好像你沒有通過使用稍微不同的簽名來正確覆蓋克隆方法。請參閱@Override註釋中的information,瞭解如何使用編譯器來處理類似的問題。

有關克隆方法的更多詳細信息,請參閱here

+0

雖然使用@Override是一個好習慣,但我不認爲方法簽名是這裏的問題。請記住,確定這是否爲重載的簽名是方法名稱+參數類型。 – 2011-04-18 01:02:24

0

如果您看到優先隊列的聲明,它不會實現可克隆接口。

public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable