0
迭代器我想遍歷結構的一個實例方法內我的數據結構的元素。這裏是我的數據結構和它的方法代碼:無法調用類型T []
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();
}
}
我的問題是在最後的方法 - toString()。當我嘗試創建itr時,會在標題中發佈錯誤。爲什麼我不能在堆棧上調用迭代器?
我假設數組不提供迭代器。這裏有一個類似的問題:http://stackoverflow.com/questions/3912765/iterator-for-array – 2014-10-05 22:43:55
不幸的是我不能使用任何集合接口。我寫了自己的迭代器類,我不得不使用它。 – 2014-10-05 22:45:05