【问题标题】:Where is the new element added in a java queuejava队列中添加的新元素在哪里
【发布时间】:2016-11-06 13:00:49
【问题描述】:

我正在使用CircularFifoQueue 创建一个队列。一切正常,但我有点困惑。列表末尾是否添加了新值?这是for循环的结果

public static CircularFifoQueue<Client> usersDelay = new CircularFifoQueue<Client>(4);

System.out.println(newValue);
   list.add(newValue);
    for(int i=0; i<list.size(); i++){
    System.out.println(i+ ": "+list.get(i));
    }

New value : 345
0: 345
--------------------------
New value : 369
0: 345
1: 369
--------------------------
New value : 444
0: 345
1: 369
2: 444
--------------------------
New value : 432
0: 345
1: 369
2: 444
3: 432
--------------------------
New value : 633
0: 369
1: 444
2: 432
3: 633
--------------------------
New value : 346
0: 444
1: 432
2: 633
3: 346
--------------------------
New value : 299
0: 432
1: 633
2: 346
3: 299
--------------------------
New value : 423
0: 633
1: 346
2: 299
3: 423
--------------------------
New value : 538
0: 346
1: 299
2: 423
3: 538
--------------------------

如果我想获取最近添加的最后 10 个元素,是否应该将列表从末尾循环到开头?

【问题讨论】:

  • list的类型是什么?
  • 链接已更新。列表包含类 Client 的自定义对象。
  • for(int i=Math.max(0,list.size()-10-1),i&lt;list.size();i++) 运行循环以打印列表的最后一个10 元素。
  • 尝试发布完整代码。似乎您已经声明了大小为4 的队列,并且根据add 函数的文档,如果您的队列已满,那么它将删除最近最少添加的元素以添加新元素。这里也发生了同样的事情,所以请检查或发布。
  • 如果我想获取最近添加的最后 10 个元素,我应该将列表从末尾循环到开头吗? 假设文档没有解释,为什么不你不试试两者都做,然后自己看看吗?

标签: java list queue


【解决方案1】:

您正在使用大小为 4 的循环 FIFO 队列。 想象一下吧。

所以当您开始向队列中添加元素时。这个过程将是这样的。

  1. 第一个元素 345 转到第 0 个索引。
  2. 第二个元素,369 转到第一个索引。
  3. 第三个元素 ,444 转到第二个索引。
  4. 第四个元素,432 转到第四个索引。 此时,由于您的队列大小仅为 4,因此您的队列已满,并且您的写入位置就在队列的 HEAD 之前。
  5. 当您添加 633 时,它自然会替换第 0 个索引(元素 345),因为它是下一个。这就是为什么现在队列的头部变为 369,而最后一个元素现在是 633。
  6. 当您现在添加 346 时,它将删除 369 并用新元素替换它,但您的新头现在是 444。

同时阅读文档。

CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its oldest element if full. The removal order of a CircularFifoQueue is based on the insertion order; elements are removed in the same order in which they were added. The iteration order is the same as the removal order.

如果您想遍历最近排序的 10 个元素,则首先将队列的大小增加到 10 个以上。然后从末尾开始遍历列表。

如果需要获取最近添加的元素(LIFO),您也可以使用堆栈,这将更自然。

【讨论】:

    猜你喜欢
    • 2012-11-26
    • 2012-08-27
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多