Ernusc
Ernusc

Reputation: 526

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

Upvotes: 0

Views: 115

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533820

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.

Upvotes: 2

Roman Vottner
Roman Vottner

Reputation: 12849

for withdraw you test for size() > 10 and for deposit size()<10 - but the opposite of <10 is not >10 but >=10

Upvotes: 0

whaity
whaity

Reputation: 11

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

Upvotes: 1

Related Questions