Since the underlying data-structure used here is an array , which is itself iterable via for-each()
, i'm wondering how much benefit implementing Iterable
will provide here.
I would appreciate if someone could review my code and suggest any further improvements.
Code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
class ResizingCircularArray<E> {
private int head = 0;
private int tail = 0;
private int size = 0; // a measure of non-null elements in the array
private E[] arr;
private void resize() {
System.out.println("resizing array to size: " + 2 * size);
@SuppressWarnings("unchecked")
E[] tempArr = (E[]) new Object[2 * size];
System.arraycopy(arr, head, tempArr, 0, size);
head = 0;
tail = head + (size - 1);
arr = tempArr;
}
@SuppressWarnings("unchecked")
public ResizingCircularArray() {
arr = (E[]) new Object[5];
}
public void enqueue(E item) {
if (item == null)
throw new java.lang.NullPointerException(
" adding null values is not allowed ");
if (size == arr.length) {
resize();
}
arr[tail++] = item;
size++;
System.out.println("head : " + head + " tail : " + tail + " , size : "
+ size);
}
public E dequeue() {
if (size == 0)
throw new java.lang.NullPointerException("size = 0");
if (size == arr.length / 4) {
resize();
}
E item = arr[head];
arr[head++] = null;
size--;
System.out.println("head : " + head + " tail : " + tail + " , size : "
+ size);
return item;
}
public boolean isEmpty() {
return size == 0;
}
public E sample(int offset) {
if (offset < 0)
throw new java.lang.IllegalArgumentException(
"negative index not allowed");
return arr[head + offset];
}
public int size() {
return size;
}
public void display() {
for (E item : arr)
System.out.print(item + " ");
System.out.println("\n");
}
public static void main(String[] args) {
ResizingCircularArray<String> r = new ResizingCircularArray<String>();
String line = null;
String[] segment, parsed;
boolean endFlag = false;
try (BufferedReader is = new BufferedReader(new FileReader(
"CircArrayPoints.txt"))) {
line = is.readLine();
segment = line.trim().split(";");
for (int i = 0; !segment[i].equals("stop") && !endFlag; i++) {
parsed = segment[i].split(" ");
switch (parsed[0]) {
case "enq":
System.out.println("adding : " + parsed[1]);
r.enqueue(parsed[1]);
r.display();
break;
case "deq":
System.out.println("dequeing : " + r.sample(0));
if (r.isEmpty()) {
System.out.println("Empty queue");
endFlag = true;
break;
}
r.dequeue();
r.display();
break;
case "disp":
r.display();
break;
default:
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Files : CircArrayPoints.txt
enq a;enq b;enq c;enq d;enq e;enq f;enq g;enq h;enq i;enq j;enq k;enq l;deq;deq;deq;deq;deq;deq;deq;deq;deq;deq;deq;deq;deq;deq;deq;deq;deq;disp;stop