public class PersistentQueue<E> { private List<E> queue; public PersistentQueue(){ //modify this constructor if neccessary, but do not remove it queue = new ArrayList<E>(); } private PersistentQueue(List<E> queue){ //modify or remove this constructor if necessary this.queue = queue; } //add other constructor if necessary /** * Returns the queue that adds an item into the tail of this queue without modifying this queue * @param e * @return * @throws IllegalArgumentException */ public PersistentQueue<E> enqueue( E e){ //TODO: make this method faster if (e == null){ throw new IllegalArgumentException(); } List<E> clone = new ArrayList<E>(queue); clone.add(e); return new PersistentQueue<E>(clone); } /** * Returns the queue that removes the object at the head of this queue without modifying this queue * * If this queue is empty,throws java.util.NoSuchElementException * @return * @throws * /java.util.NoSuchElementException */ public PersistentQueue<E> dequeue(){ //TODO:make this method faster if ( queue.isEmpty()){ throw new NoSuchElementException(); } List<E> clone = new ArrayList<E>(queue); clone.remove(0); return new PersistentQueue<E>(clone); } public E peek(){ //modify this method if needed if (queue.isEmpty()){ throw new NoSuchElementException(); } return queue.get(0); } public int size(){ //modify this method if necessary return queue.size(); }
public static void main(String[] args){ PersistentQueue<String> ps = new PersistentQueue<String>(); ps.enqueue("string"); System.out.print(ps.peek()); } }
分享到:
------解决方案-------------------- 我怎么感觉可以就这样写呢 public class PersistentQueue<E> extends ArrayList<E> ------解决方案-------------------- 哪里感觉出效率低呢 ------解决方案-------------------- 用ArrayList去实现队列就不可能快起来。 ------解决方案--------------------