简体   繁体   中英

What's wrong with Queue?

I faced with problem. Code:

// withdraw method
 public void withdraw(long n)
{
    this.n = n;
    Action a = new WithDraw();
    a.doAction(n);
    **if(actionsList.size() > 10)**
    {
        actionsList.poll();
        actionsList.offer(a);

    } else
    {
        actionsList.offer(a);
    }

}

// Deposit method goes here

    public void deposit(long n)
{
  this.n = n;
  Action a = new Deposit();
  a.doAction(n);
  **if(actionsList.size()<10)**
  {

      actionsList.offer(a);
  } else 
  {
      actionsList.poll();
      actionsList.offer(a);
  }

}

The Main function looks like this:

    acc1.deposit(1);
    acc1.withdraw(2);
    acc1.deposit(3);
    acc1.withdraw(4);
    acc1.deposit(5);
    acc1.withdraw(6);
    acc1.deposit(7);
    acc1.withdraw(8);
    acc1.deposit(9);
    acc1.withdraw(10);
    acc1.deposit(11);
    acc1.withdraw(12);
    acc1.deposit(13);
    acc1.withdraw(14);
    acc1.deposit(15);
    acc1.displayActions();

I need 10 last added elements. After this I got printed 11 elements not 10. What's wrong with that? Maybe I do not understand Queue size() correctly?

ADDED print method:

public void displayActions()
    {
        for(Action s : actionsList)
        {
            System.out.println(s);
        }
    }

When the size is equal to 10, you can still add another, so you get 11.

As others have mentioned the opposite of > is <= also >= is < and == is != In short you should try to keep your code as consistent as possible. If code is supposed to do the same thing, you should write it the same way, if not use a method to do them both.

public void withdraw(long n) {
    queueAction(new Withdrawal(n));
}

public void deposit(long n) {
    queueAction(new Deposit(n));
}

void queueAction(Action action) {
    action.doAction();
    if (actionsList.size() >= 10)
        actionsList.poll();
    actionsList.offer(aaction);
}

I have taken out this.n = n; as this doesn't appear to do anything and I don't see the point of performing an action before you queue it...

I am not sure why I would want to silently discard any deposits older than the last 10. I would like to be able to ignore some of my withdrawals though.

Is this just not a simple case of the .size() starting at 0?

IE, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 = 11

对于withdraw您需要测试size() > 10以及deposit size()<10size()<10的反面不是> 10而是> = 10

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