问题描述
我正在尝试 Java 中的接口,我想为一个非常简单的堆栈实现一个通用接口,使用 pop()
和 push()
方法和一个迭代器。
问题是我不知道如何在接口中指定迭代器。无论我尝试哪种方式,我都会得到
Main.java:32: error: for-each not applicable to expression type
for (Integer i : ss)
^
required: array or java.lang.Iterable
found: Stack<Integer>
代码如下:
interface Stack<T> {
boolean push(T t);
boolean pop();
//Iterator<T> iterator(); // How to indicate it needs,and will have,an iterator?
}
public class DynamicStack<T> implements Iterable<T>,Stack<T>
{
// implementation-specific variables go here
public DynamicStack() {
//...
}
public boolean push(T t) {
//...
}
public boolean pop() {
//...
}
private class StackIterator implements Iterator<T> {
DynamicStack<T> stk;
//...
// Iterator constructor
private StackIterator(DynamicStack<T> stk)
{
//...
}
public boolean hasNext()
{
//...
}
public T next() throws NoSuchElementException
{
//...
}
public void remove() throws UnsupportedOperationException
{
throw new UnsupportedOperationException(); // I chose not to implement this one
}
}
// Iterator method
public Iterator<T> iterator()
{
return new StackIterator(this);
}
}
public class StaticStack<T> implements Iterable<T>,Stack<T>
{
// implementation-specific variables go here
public StaticStack()
{
//...
}
public boolean push(T t)
{
//...
}
public boolean pop()
{
//...
}
private class StackIterator implements Iterator<T>
{
StaticStack<T> stk;
//...
private StackIterator(StaticStack<T> stk)
{
//...
}
public boolean hasNext()
{
//...
}
public T next() throws NoSuchElementException
{
//...
}
public void remove() throws UnsupportedOperationException
{
//...
}
}
// Iterator method
public Iterator<T> iterator()
{
return new StackIterator(this);
}
}
Main 在创建每种类型的几个堆栈并添加一些元素之后,简单地执行此操作:
public static void showStuff(Stack<Integer> ss)
{
for (Integer i : ss)
System.out.print(i+" ");
System.out.println();
}
解决方法
在您的测试类中,您对 Stack
接口进行操作,因此该接口需要符合 Iterable
。在这种情况下,如果 StaticStack
没有实现,DynamicStack
或 Stack
没有帮助。
要使 Stack 能够用作 Iterable,只需更改您的 Stack 以扩展 Iterable:
public interface Stack<T> extends Iterable<T> {
boolean push(T t);
boolean pop();
}
和
public class StaticStack<T> implements Stack<T>
并且代码运行得很好:
public class Tester {
public static void main(String args[]) {
Stack<Integer> ss = new StaticStack<>();
for (Integer i : ss)
System.out.print(i+" ");
System.out.println();
}
}
,
您需要类来实现 Iterable<T>
,它具有 iterator()
方法,该方法返回 Iterator<T>
。