入队列表方法

时间:2013-03-19 15:46:19

标签: java list arraylist queue

有没有办法让这种方法更快入队?我正在尝试为此方法添加性能测试,并想知道是否有替代方案。

  import java.util.ArrayList;
  import java.util.List;
  import java.util.NoSuchElementException;

  public class ImmutableQueueImpl<E> implements ImmutableQueue<E> {
      private     List<E> queue;
      public ImmutableQueueImpl() { 
        queue = new ArrayList<E>();
      }

      private ImmutableQueueImpl(List<E> queue) {
        this.queue = queue; }

      @Override
      public ImmutableQueue<E> enqueue(E e) {
        if (e == null) {
         throw new IllegalArgumentException();
        }
        List<E> clone = new ArrayList<E>(queue); clone.add(e);
        return new ImmutableQueueImpl<E>(clone);
      }

      @Override
      public ImmutableQueue<E> dequeue() {
         if (queue.isEmpty()) {
            throw new NoSuchElementException();
         }
         List<E> clone = new ArrayList<E>(queue); 
         clone.remove(0);
         return new ImmutableQueueImpl<E>(clone);
      }

      @Override 
      public E peek() {
        if (queue.isEmpty()) {
          throw new NoSuchElementException();
        }
        return queue.get(0); 
      }

     @Override 
     public int size() {
      return queue.size();
     }
    }

修改    我添加了完整的代码供参考。希望有所帮助

1 个答案:

答案 0 :(得分:0)

在内部使用2个不可变列表,可以在不可变队列中获取O(1)进行入队/出队操作。

以下是从Scala book借来的代码:

class Queue[T](
  private val leading: List[T],
  private val trailing: List[T]
) {
  private def mirror =
    if (leading.isEmpty) new Queue(trailing.reverse, Nil)
    else this

  def head = mirror.leading.head

  def tail = {
    val q = mirror
    new Queue(q.leading.tail, q.trailing)
  }

  def append(x: T) = new Queue(leading, x :: trailing)
}