如何使用迭代器取回一堆整数?如果我使用 Objects 但不是 int,我的代码适用于语句。如果我对 Objects 使用 for 语句,它就可以工作。它与整数自动装箱有关吗?
public class Simulator {
public static void main(String[] args) {
Stack<Integer> s = new Stack<Integer>();
s.insert(15);
s.insert(25);
s.insert(7);
for ( int t : s) {
System.out.println(t);
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package stack;
import java.util.Iterator;
/**
*
* @author
*/
public class Stack<Item> implements Iterable {
/**
* @param args the command line arguments
*/
private Item[] arr;
private int n;
public Stack() {
System.out.println("Stack initialized");
arr = (Item[]) new Object[1];
n = 0;
}
public void insert(Item element) {
if (n == arr.length) {
resize(arr.length * 2);
}
arr[n++] = element;
}
@Override
public Iterator iterator() {
return new ListIterator();
}
private class ListIterator implements Iterator<Item> {
private int i = n;
@Override
public boolean hasNext() {
return i > 0;
}
@Override
public Item next() {
return arr[--i];
}
@Override
public void remove() {
}
}
// resize the underlying array holding the elements
private void resize(int capacity) {
assert capacity >= n;
Item[] temp = (Item[]) new Object[capacity];
for (int i = 0; i < n; i++) {
temp[i] = arr[i];
}
arr = temp;
}
}