简体   繁体   中英

How do I overload LinkedList's add method?

I have to overload LinkedList's add method so that it add new CustomerOrders in order by their Order Number(an integer). Here is the code I have so far.

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;
}

When I enter orders with order numbers 1 through 5 the list is 1,5,4,3,2. What I want is for the list to be 1,2,3,4,5. Can anyone point out where I went wrong and give me some tips to fix it?

I think the data structure that you actually want is a PriorityQueue .

As far as the bug in your code goes, I'm pretty sure that the problem is that currently i.add(order) will insert the new element after a smaller element, whereas to get the order you want you would need to insert it before a larger element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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