2012-10-02 32 views
0

我必須重載LinkedList的add方法,以便它們的訂單號(整數)順序添加新的CustomerOrders。這是我迄今爲止的代碼。如何重載LinkedList的add方法?

public boolean add(CustomerOrder order) 
{ 

    ListIterator<CustomerOrder> i = this.listIterator(); 

    if(!(i.hasNext())) //there are no orders in the list 
    { 
     i.add(order); 
     return true; 
    } 


    while(i.hasNext()) 
    { 
     int compare = order.compareTo(i.next(), 1);//compareTo returns 0 if the orders have the same order number, 1 if order greater order num, -1 if order has lower order num 

     if(compare == 0) //can't add the order if another order has the same order num 
     { 
      return false; 
     } 
     else 
     { 
      if(compare == 1) //order is greater than i.next() 
      { 
       i.add(order); //my guess is that the problem is here 
       return true; 
      } 
     } 
    } 

    return false; 
} 

當我輸入訂單編號1到5時,列表爲1,5,4,3,2。我想要的是該列表爲1,2,3,4,5。任何人都可以指出我出錯的地方,給我一些提示來解決它嗎?

+2

覆蓋或超載? – Elbek

+0

這不是LinkedList子類的好理由。 – duffymo

回答

3

我認爲你實際需要的數據結構是PriorityQueue

至於在你的代碼的bug去,我敢肯定,問題是,目前i.add(order)將一個元素之後插入新元素,而得到你想要的,你需要的順序將其插入之前 a 元件。