I'm trying to fully implement a Deque without using the one already made in the java library. my code compiles, but the output is not quite as expected. for instance, the capacity is supposed to be given to the class as a parameter, but the result shows that the real capacity ends up being 1 lower than the amount specified.
another issue that Iæm having is that the queue is supposed to work as first-in-first-out. but this is not represented in the results. any ideas?
public class ArrayDeque<E> implements IDeque<E> {
private int capacity;
private E[] array;
private int front;
private int end;
private int size;
public ArrayDeque(int capacity) {
this.array = (E[]) new Object[capacity];
this.capacity = capacity - 1;
front = 1;
end = 0;
size = 0;
}
private boolean isFull() {
return (size == capacity);
}
private boolean isEmpty() {
return (size == 0);
}
@Override
public int size() {
return size;
}
@Override
public void addFirst(E elem) throws DequeFullException {
if (isFull())
throw new DequeFullException("samlingen er full!");
array[front] = elem;
front = (front + 1) % capacity; // use modulo to make sure the front restarts from initial position once it reaches capacity
size++;
}
@Override
public E pullFirst() throws DequeEmptyException {
if (isEmpty())
throw new DequeEmptyException("Samlingen er tom!");
front = (front - 1) % capacity;
size--;
return array[front];
}
@Override
public E peekFirst() throws DequeEmptyException {
if (isEmpty())
throw new DequeEmptyException("samlingen er tom!");
System.out.println(array[(front - 1) % capacity]);
return array[(front - 1) % capacity];
}
@Override
public void addLast(E elem) throws DequeFullException {
if (isFull())
throw new DequeFullException("samlingen er full!");
array[end] = elem;
end = (end - 1) % capacity;
size++;
}
@Override
public E pullLast() throws DequeEmptyException {
if (isEmpty())
throw new DequeEmptyException("samlingen er tom!");
end = (end + 1) % capacity;
size--;
return array[end];
}
@Override
public E peekLast() throws DequeEmptyException {
if (isEmpty())
throw new DequeEmptyException("samlingen er tom!");
System.out.println(array[(end + 1) % capacity]);
return array[(end + 1) % capacity];
}
}
public class Main {
public static void main(String[] args){
ArrayDeque<String> deque = new ArrayDeque<>(6);
deque.addFirst("first");
deque.addFirst("second");
deque.addFirst("third");
deque.addFirst("fourth");
deque.peekFirst();
deque.peekLast();
deque.addLast("fourth");
deque.addLast("last");
deque.peekLast();
deque.size();
}
}
this.capacity = capacity - 1;is the cause?