import java.util.ArrayList;
import java.util.List;
public class QueueImplList<E> {
private int maxSize = 0;
private int size = 0;
private int head = 0;
private List<E> list = new ArrayList<>();
public QueueImplList(int maxSize) {
this.maxSize = maxSize;
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == maxSize;
}
public int size() {
return size;
}
public boolean add(E value) {
if(!isFull()) {
list.add(value);
size ++;
return true;
} else {
if(head >= 2* maxSize) { //reclaim space in List
System.out.println("house keeping");
for(int i = 0; i < size; i++) {
list.set(i, list.get(head + i));
head = 0;
}
for(int i = size + 1; i < head + size; i++) {
list.remove(i);
}
}
return false;
}
}
public E take() {
if(!isEmpty()) {
E value = list.get(head);
head ++;
size --;
return value;
}
return null;
}
public static void main(String... args) {
QueueImplList<Integer> queue = new QueueImplList<>(3);
queue.add(1);
queue.add(2);
queue.add(3);
queue.add(4);
System.out.println(queue.take());
System.out.println(queue.take());
System.out.println(queue.take());
System.out.println(queue.take());
queue.add(1);
queue.add(2);
queue.add(3);
queue.add(4);
System.out.println(queue.take());
System.out.println(queue.take());
System.out.println(queue.take());
System.out.println(queue.take());
queue.add(1);
queue.add(2);
queue.add(3);
queue.add(4);
System.out.println(queue.take());
System.out.println(queue.take());
System.out.println(queue.take());
System.out.println(queue.take());
queue.add(1);
queue.add(2);
queue.add(3);
queue.add(4);
System.out.println(queue.take());
System.out.println(queue.take());
System.out.println(queue.take());
System.out.println(queue.take());
queue.add(1);
queue.add(2);
queue.add(3);
queue.add(4);
System.out.println(queue.take());
System.out.println(queue.take());
System.out.println(queue.take());
System.out.println(queue.take());
}
}