이 코드는 알고리즘 텍스트에서 있지만, 중첩 된 클래스 및 인터페이스에 관한 문제가 약간 있습니다 - 실제로 내 혼동의 90 %는이 코드가 인터페이스를 구현하는 방법에서 발생합니다. 다시 말하지만,이 질문은 알고리즘 자체에 관한 것이 아닙니다.중첩 된 클래스 및 구현 자바에서
이 코드는 중첩 클래스를 사용하여 ResizingArrayStack의 개인 인스턴스 변수에 액세스 할 수 있도록합니다.이 텍스트는 캡슐화를 위해 모든 인스턴스 변수를 private로 선언하는 규칙을 사용합니다.
public Iterator<Item> { Iterator<Item> iterator(); } // ignore the quotes
과 Iterator
인터페이스는 이것이다 :
Iterable
인터페이스는 이것이다
public interface Iterator<Item> { boolean hasNext(); Item next(); void remove(); }
을 그리고이 모든 아래의 코드에 연결하는 방법 내 질문입니다.
상위 클래스는 Iterable 인터페이스를 구현하지만, ReverseArrayIterator가 Iterator를 구현할 때 바로 Iterator 인터페이스가 제공되는 곳은 어디입니까? Iterator 인스턴스 메소드 또는 Iterable 인터페이스에서 오는 것입니까? Intuit는 Iterator 인스턴스 메소드와 궁극적으로 Iterable 인터페이스 (작동 확장과 같은 종류)에서 직접 구현된다는 것을 알려줍니다.
OOP 지식이 부족하여 죄송합니다.이 텍스트는 간략하게 이야기하고 있으며,이 사실을 알 필요가 없다는 말을 들었습니다. 알고리즘),하지만 나는 그것을 이해해야한다. 나는 이걸 내 마음에서 벗어날 수 없다. 미리 감사드립니다.
// 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