I'm stuck on a method right now. I need to write a method, public boolean equals(CircularArray <T> m)
which test whether two FIFO queues implemented as circular arrays have the same elements in the same order. For example, suppose that c
and d
are both of type CircularArray<Integer>
with the following data fields:
c.elements = [null,null,7,11,7,4,null] d.elements[7,4,null,7,11]
c.start = 2 d.start = 3
c.end = 6 d.end = 2
Then c.equals(d)
should return true
, because conceptually these are both implementations of the queue with elements 7,11,7,4
.
I've written a method that should create two new arrays containing the elements in the correct order without the null elements. The problem I am having is that, while I think it's conceptually correct, I am running into errors. Attached is my method, and the whole program.
The whole program:
// FIFO Queue implemented as circular array.
// end field points after last element. Thus end==start for empty array.
public class CircularArray<T> {
private T[] elements;
int start;
int end;
public CircularArray(T[] elts) {
elements = elts;
start = 0;
end = 0;
}
public boolean empty() { return end == start; }
public boolean full() {
return ((start == 0 && end == elements.length-1) || end == start-1);
}
public void add(T x) {
if (!full()) {
elements[end] = x;
end++;
if (end == elements.length) end=0;
}
}
public T first() { return elements[start]; }
public T pop() {
if (!empty()) {
T x = elements[start];
start = start + 1;
if (start == elements.length) start = 0;
return x;
}
else return null;
}
public String toString() {
String S = "[";
for (int i = start; i != end; ) {
S = S + elements[i].toString() + " ";
i++;
if (i == elements.length) i = 0;
}
return S + "]";
}
public static void main(String[] args) {
CircularArray<Integer> Q = new CircularArray<Integer>(new Integer[8]);
Q.add(null);
Q.add(null);
Q.add(7);
Q.add(11);
Q.add(7);
Q.add(4);
Q.add(null);
Q.start = 2;
Q.end = 6;
CircularArray<Integer> F = new CircularArray<Integer>(new Integer[5]);
F.add(7);
F.add(4);
F.add(null);
F.add(7);
F.add(11);
F.start = 3;
F.end = 2;
System.out.println(Q.equals(F));
}
}
My method:
public boolean equals(CircularArray<T> m)
{
int a = 0;
int b = 0;
T[] elements1;
T[] elements2;
for(int i = start; i != end;)
{
elements1[a] = elements[i];
a++;
if(i==elements.length) i=0;
}
for(int i = m.start; i != m.end;)
{
elements2[b] = elements[i];
b++;
if(i==m.elements.length) i=0;
}
for(int i = 0; i <= elements.length;)
{
if(elements1[i] == elements2[i])
{
return true;
}
else
{
return false;
}
}
return true;
}