有没有办法让这个方法更快地排队?我正在尝试为此方法添加性能测试,并想知道是否有替代方法。
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();
}
}
编辑 我添加了完整的代码以供参考。希望有帮助