【问题标题】:How to get a particular element from Queue?如何从队列中获取特定元素?
【发布时间】:2014-03-17 12:01:25
【问题描述】:

ArrayList不同,Queue中没有get(int index)方法来检索指定位置的元素。

谁能告诉我如何在Queue 中实现这一点?

谢谢。

【问题讨论】:

  • 向下转换到您的特定 Queue 实现,如果它支持该操作。
  • 队列为先进先出。为什么会有get(int index) 方法?将您的数据结构更改为适当的结构。
  • 队列为先进先出。你不能在队列中实现这一点。它会破坏队列的功能。
  • 使用链表。这是一个可以从中间访问的完美队列。

标签: java collections


【解决方案1】:

您可以从队列中删除元素,直到达到所需的元素。您可以在队列末尾重新添加已删除的元素或将它们放入不同的队列中(并在到达所需元素后添加其余元素)。

不过,你真的不应该使用这样的队列!

public static <T> T get(Queue<T> queue, int index) {
    synchronized (queue) {
        if (queue == null) {
            return null;
        }

        int size = queue.size();
        if (index < 0 || size < index + 1) {
            return null;
        }

        T element = null;
        for (int i = 0; i < size; i++) {
            if (i == index) {
                element = queue.remove();
            } else {
                queue.add(queue.remove());
            }
        }

        return element;     
    }
}

【讨论】:

    【解决方案2】:

    队列以先进先出 (FIFO) 方式运行,因此为了访问特定元素,必须将元素移除并存储在辅助队列中,直到识别出正在搜索的元素

    【讨论】:

      【解决方案3】:
      public static Object retrieveElement(int index, Queue q) {
          Iterator it = q.iterator();
          int count = 0;
          while (it.hasNext()) {
              Object e = it.next();
              if (count == index) {
                  it.remove();
                  return e;
              }
              count++;
          }
          return null;
      }
      

      【讨论】:

        【解决方案4】:

        按索引访问元素不是队列概念的一部分。

        如果您需要按索引访问元素,则需要一个列表,而不是队列。

        【讨论】:

          【解决方案5】:
          public static <T> T getFromQueue(Queue<T> queue, int index){
              if(index>=queue.size()){
                  throw new IndexOutOfBoundsException("index="+index+",size="+queue.size());
              }
              Queue<T> queueCopy = new LinkedList<T>(queue);
              for(int i=0; i<index; i++){
                  queueCopy.remove();
              }
              return queueCopy.peek();
          }
          

          【讨论】:

            【解决方案6】:
            private static  List<Individual> queueToList(Queue<Individual> archive) {
                  List<Individual> list = new LinkedList<Individual>();
                  Iterator<Individual> it = archive.iterator();
                  while(it.hasNext()){
                     list.add(it.next());
                  }
                return list;
            }
            

            【讨论】:

              【解决方案7】:

              队列的概念基本上是FIFO(先进先出)。因此访问特定索引或队列中的元素是不可能的。另一种方法是获取需要删除的特定元素,除非并且直到你得到它。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2015-10-02
                • 1970-01-01
                • 1970-01-01
                • 2020-06-18
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多