blob: bd86cdf73b4ee4131e08c81eff7b921da5dedeb6 [file] [log] [blame]
/*******************************************************************************
* Copyright (c) 2015 Oracle. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0, which accompanies this distribution
* and is available at http://www.eclipse.org/legal/epl-v10.html.
*
* Contributors:
* Oracle - initial API and implementation
******************************************************************************/
package org.eclipse.jpt.common.utility.internal.deque;
import java.io.Serializable;
import java.util.List;
import java.util.NoSuchElementException;
import org.eclipse.jpt.common.utility.deque.Deque;
/**
* Adapt a {@link List} to the {@link Deque} interface.
* Head elements are dequeueHeadd from the front of the list (i.e. index 0);
* while tail elements are dequeueHeadd from the end of the list.
* @param <E> the type of elements maintained by the deque
* @see DequeTools
*/
public class ListDeque<E>
implements Deque<E>, Serializable
{
private List<E> list;
private static final long serialVersionUID = 1L;
// ********** constructors **********
/**
* Construct a deque, adapting the specified list.
* The deque's head will dequeueHead its elements in the same
* order they are returned by the list's iterator (i.e. the
* first element returned by the list's iterator will be the
* first element returned by {@link #dequeueHead()}).
*/
public ListDeque(List<E> list) {
super();
this.list = list;
}
// ********** Deque implementation **********
public void enqueueTail(E element) {
this.list.add(element);
}
public void enqueueHead(E element) {
this.list.add(0, element);
}
public E dequeueHead() {
if (this.list.size() == 0) {
throw new NoSuchElementException();
}
return this.list.remove(0);
}
public E dequeueTail() {
int size = this.list.size();
if (size == 0) {
throw new NoSuchElementException();
}
return this.list.remove(size - 1);
}
public E peekHead() {
if (this.list.size() == 0) {
throw new NoSuchElementException();
}
return this.list.get(0);
}
public E peekTail() {
int size = this.list.size();
if (size == 0) {
throw new NoSuchElementException();
}
return this.list.get(size - 1);
}
public boolean isEmpty() {
return this.list.isEmpty();
}
// ********** standard methods **********
@Override
public String toString() {
return this.list.toString();
}
}