2012-10-02 103 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 元件。