如何在Java类中迭代私有集合成员?

时间:2015-12-02 19:51:59

标签: java private public

所以这就是这个有一个领域的类,比方说吧 Stack<Integer> changed_vertices并且私有可迭代。如果它是一个原始类型变量,我会写一个getter来从其他类中获取值。但是我需要从外部(从其他类)迭代这个堆栈。

我可以实现什么样的'getter'来迭代这个堆栈?由于某些原因,我无法将其从私有更改为 public

感谢。

1 个答案:

答案 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);
}

这完全取决于调用者需要做什么和/或应该允许使用堆栈。