I'm trying to iterate over the elements of my data structure within an instance method of the structure. Here is the code for my data structure and its methods:
import java.util.Iterator;
public class DropOutStackArray<T> implements DropOutStack<T>{
private static final int CAP = 10;
private int bottom, top, size;
private T[] cstack;
public static void main(String[] args){
//System.out.println(2%10);
//int[] a = new int[10];
//System.out.println(a.length);
}
private class MyIterator implements Iterator<T>{
private int curr = 0;
@Override
public boolean hasNext() {
return this.curr != DropOutStackArray.this.size;
}
@Override
public T next() {
if(hasNext()){
return cstack[curr++];
}
return null;
}
public void remove(){
if(curr == 0)
return;
cstack[--curr] = cstack[--size];
cstack[curr] = null;
}
}
@Override
public Iterator<T> iterator() {
// TODO Auto-generated method stub
return new MyIterator();
}
public DropOutStackArray(){
this.cstack = (T[]) new Object[CAP];
this.bottom = 0; this.top = 0;
this.size = 0;
}
public DropOutStackArray(final int INCAP){
this.cstack = (T[]) new Object[INCAP];
this.bottom = 0; this.top = 0;
this.size = 0;
}
@Override
public void push(T data) {
// TODO Auto-generated method stub
if(this.size == this.cstack.length){
this.cstack[bottom] = data;
this.bottom = (this.bottom + 1) % this.cstack.length;
this.top = (this.top + 1) % this.cstack.length;
}
this.cstack[this.top] = data;
this.top = (this.top + 1) % this.cstack.length;
this.size++;
}
@Override
public T pop(){
T popped;
if(!isEmpty()){
int length = this.cstack.length;
this.top = (this.top + length - 1) % length;
popped = this.cstack[this.top];
this.cstack[this.top] = null;
this.size--;
}else{
throw new StackEmptyException();
}
return popped;
}
@Override
public T peek() {
// TODO Auto-generated method stub
if(isEmpty()){
throw new StackEmptyException();
}
T peeked = this.cstack[this.top-1];
return peeked;
}
@Override
public int size() {
return this.size;
}
@Override
public boolean isEmpty() {
if(this.size == 0){
return true;
}
return false;
}
public String toString(){
Iterator<T> itr = this.cstack.iterator();
}
}
My issue is in the very last method - toString(). When I try creating itr, I get the error posted in the title. Why can't I call the iterator on cstack?