所以这就是这个有一个领域的类,比方说吧
Stack<Integer> changed_vertices
并且私有和可迭代。如果它是一个原始类型变量,我会写一个getter来从其他类中获取值。但是我需要从外部(从其他类)迭代这个堆栈。
我可以实现什么样的'getter'来迭代这个堆栈?由于某些原因,我无法将其从私有更改为 public 。
感谢。
答案 0 :(得分:1)
您有多种选择。
只需返回堆栈:
public Stack<Integer> getChangedVertices()
{
return changed_vertices;
}
将堆栈作为不可修改的List返回:
public List<Integer> getChangedVertices()
{
return Collections.unmodifiableList(changed_vertices);
}
返回一个迭代器:
public Iterator<Integer> getChangedVertices()
{
return changed_vertices.iterator();
}
接受消费者,并将堆栈内容推送到消费者
public void consumeChangedVertices(Consumer<Integer> action)
{
changed_vertices.stream().forEach(action);
}
等
这完全取决于调用者需要做什么和/或应该允许使用堆栈。