I'm trying to implement a queue ADT using an array for a homework assignment (were it up to me I would be using a linked list, but I guess the professor wants us to learn new things or something XD). Anyway, I'm working on a method to add an element to the end of the queue, this same method should create a new re-sized array if it gets out of bounds, and this is the method I'm struggling with (the enqueue() method). Here is my code:
import java.util.Arrays;
public class Queue<T> implements QueueInterface<T> {
private T[] a;
private int sz;
public Queue(int capacity) {
sz = 0;
@SuppressWarnings("unchecked")
T[] tempQueue = (T[])new Object[capacity];
a= tempQueue;
}
public void enqueue(T newEntry) {
try {
for (int i=0; i<a.length; i++) {
if (a[i] == null) {
a[i] = newEntry;
break;
}
}
sz++;
}
catch (ArrayIndexOutOfBoundsException e) {
@SuppressWarnings("unchecked")
T[] tempQueue = (T[])new Object[a.length*+5];
a= tempQueue;
for (int i=0; i<a.length; i++) {
if (a[i] == null) {
a[i] = newEntry;
break;
}
}
}
}
public T dequeue() {
T result = a[0];
a[0] = null;
for (int i=1; i<a.length;i++) {
a[i-1] = a[i];
}
sz--;
return result;
}
public T getFront() {
return a[0];
}
public boolean isEmpty() {
for (int i=0; i<a.length; i++) {
if (a[i] != null) {
return false;
}
}
return true;
}
public void clear() {
for (int i=0; i<a.length; i++) {
a[i] = null;
sz--;
}
}
@Override
public String toString() {
return "Queue [a=" + Arrays.toString(a) + ", sz=" + sz + "]";
}
}
Thanks so much for your time everyone!!!