繁体   English   中英

如何重载LinkedList的add方法?

[英]How do I overload LinkedList's add method?

我必须重载LinkedList的add方法,以便它按其Order Number(整数)顺序添加新的CustomerOrders。 这是我到目前为止的代码。

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。 谁能指出我出了问题的地方,并给我一些解决办法?

我认为您实际需要的数据结构是PriorityQueue

就代码中的错误而言,我很确定问题是当前i.add(order)一个较小的元素之后插入新元素,而要获得所需的顺序,则需要将其插入 更大的元素之前

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM