尽管这段代码来自算法文本,但我在嵌套类和接口方面遇到了一些麻烦 - 实际上,90%的混淆来自于该代码如何实现接口。同样,这个问题不是关于算法本身。在java中嵌套的类和实现接口
据我所知,此代码使用嵌套类,以便它可以访问ResizingArrayStack中的私有实例变量(本文使用约定将所有实例变量声明为私有封装)。
的Iterable
界面是这样的:
public Iterator<Item> { Iterator<Item> iterator(); } // ignore the quotes
和Iterator
界面是这样的:
public interface Iterator<Item> { boolean hasNext(); Item next(); void remove(); }
我的问题是如何将所有这些在下面所示的代码连接。
父类实现Iterable接口,但当ReverseArrayIterator实现Iterator时,Iterator接口直接来自哪里?它来自Iterator实例方法还是来自Iterable接口?直觉告诉我,它直接从Iterator实例方法实现,最终从Iterable接口实现(有点像扩展工作?)。
对不起,我没有面向对象的知识..这个文本只是简单地谈论它,并且我被告知我不必知道任何这些(并且我可能不知道,只要我理解了算法),但我必须理解它大声笑。我无法将这一点从我的脑海中解放出来。提前致谢。
// from http://algs4.cs.princeton.edu/13stacks/ResizingArrayStack.java.html
import java.util.Iterator;
import java.util.NoSuchElementException;
public class ResizingArrayStack<Item> implements Iterable<Item> {
private Item[] a; // array of items
private int N; // number of elements on stack
// create an empty stack
public ResizingArrayStack() {
a = (Item[]) new Object[2];
}
public boolean isEmpty() { return N == 0; }
public int size() { return N; }
// 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] = a[i];
}
a = temp;
}
// push a new item onto the stack
public void push(Item item) {
if (N == a.length) resize(2*a.length); // double size of array if necessary
a[N++] = item; // add item
}
// delete and return the item most recently added
public Item pop() {
if (isEmpty()) { throw new RuntimeException("Stack underflow error"); }
Item item = a[N-1];
a[N-1] = null; // to avoid loitering
N--;
// shrink size of array if necessary
if (N > 0 && N == a.length/4) resize(a.length/2);
return item;
}
public Iterator<Item> iterator() { return new ReverseArrayIterator(); }
// an iterator, doesn't implement remove() since it's optional
private class ReverseArrayIterator implements Iterator<Item> {
private int i = N;
public boolean hasNext() { return i > 0; }
public void remove() { throw new UnsupportedOperationException(); }
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
return a[--i];
}
}
}
谢谢。我花了一段时间才得到它(之前没有OOP经验),但是我想我已经足够了解你所说的,看看代码试图做什么。 – user1164937