Interview Question
Country: United States
First of all, it's obvious that the second new operation in enqueue() and dequeue() method is rebundant.
Then, as copy is so often to do, I suggest that your PersistentQueue implement Cloneable interface. Thus the way of creating a copy in enqueue() and dequeue() method could use clone() method, which is faster than new. This might be an improvement.
public class PersistentQueue<E> implements Cloneable{
private List<E> queue;
public PersistantQueue<E> clone(){
PersistantQueue<E> copy = null;
try{
copy = (PersistantQueue<E>)super.clone();
copy.queue = (list<E>)this.queue.clone();
}
catch(CloneNotSupportedException e){
e.printStackTrace();
}
return copy;
}
public PersistantQueue<E> enqueue(E e){
if(e == null){
throw new IllegalArgumentException();
}
List<E> copy = clone();
copy.add(e);
return copy;
}
public PersistantQueue<E> dequeue(){
if(queue.isEmpty()){
throw new NoSuchElementException();
}
List<E> copy = clone();
copy.remove(0);
return copy;
}
}
Decorator Pattern
- Sunil Singhal November 03, 2013