简体   繁体   English

队列出了什么问题?

[英]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: Main函数如下所示:

    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. 我需要10个最后添加的元素。 After this I got printed 11 elements not 10. What's wrong with that? 在此之后,我打印了11个元素,而不是10个。这有什么问题? Maybe I do not understand Queue size() correctly? 也许我无法正确理解Queue size()?

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. 当大小等于10时,您仍然可以添加另一个,因此得到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; 我把这个拿出来了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. 我不确定为什么我要静默丢弃任何比最后10天还早的存款。我想忽略掉我的部分提款。

Is this just not a simple case of the .size() starting at 0? 这不是.size()从0开始的简单情况吗?

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

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

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

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