I'm trying to implement a deque data structure with an iterator in Java using array. Please help to review and point out things that I can improve on.
public class Deque<Item> implements Iterable<Item> {
private Item[] a; // the array.
private int itemCount; // number of objects the array holds at any given point in time.
private int head; //last filled position from Front
private int tail; //last filled position from END
private int size; // size of array.
public Deque() {
// construct an empty deque
size = 2;
a = (Item[])new Object[size];
itemCount = 0;
head = 0;
tail = 0;
}
public boolean isEmpty() {
// is the deque empty?
return (itemCount == 0);
}
public int size() {
// return the number of items on the deque
return itemCount;
}
public void addFirst(Item item) {
try {
if (item == null) {
throw new IllegalArgumentException("item cannot be null");
}
}
catch (NullPointerException ex) {
throw new IllegalArgumentException("item cannot be null");
}
if (isEmpty()) {
addLast(item);
//return;
} else if (head == 0) {
resize(size);
head--;
a[head] = item;
itemCount++;
//return;
} else {
head--;
a[head] = item;
itemCount++;
//return;
}
return;
}
private void resize (int currentSize) {
//resize array to squared of current size.
int newSize = currentSize * currentSize;
int newStart = (currentSize * (currentSize - 1))/2;
int newHead = newStart;
Item[] newA = (Item[]) new Object[newSize];
for (int j = itemCount; j > 0; j--) {
newA[newStart++] = a[head++];
}
head = newHead;
tail = newStart - 1;
size = newSize;
a = newA;
return;
}
public void addLast(Item item) {
if (isEmpty()) {
tail++;
a[tail] = item;
head = tail;
itemCount++;
//return;
}
else if ( tail == (size -1)) {
resize(size);
tail++;
a[tail] = item;
itemCount++;
}
return;
}
public Item removeFirst() {
// remove and return the item from the front
Item k;
if (isEmpty()) throw new java.util.NoSuchElementException("Empty Deque");
else {
k = a[head];
a[head] = null;
head --;
//start --;
itemCount--;
}
return k;
}
public Item removeLast() {
// remove and return the item from the end
Item k;
if (isEmpty()) throw new java.util.NoSuchElementException("Empty Deque");
else {
k = a[tail];
a[tail] = null;
tail --;
//end --;
itemCount--;
}
return k;
}
public Iterator<Item> iterator() {
// return an iterator over items in order from front to end
return new DequeIterator();
}
private class DequeIterator implements Iterator<Item> {
private int startpos;
private int size;
public DequeIterator () {
startpos = head;
size = itemCount;
}
public boolean hasNext() {
return (size != 0);
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if (hasNext()) {
size--;
return a[startpos++];
}
throw new NoSuchElementException();
}
}
}