gpt4 book ai didi

java - 为什么java中的集合没有只读迭代器的概念?

转载 作者:行者123 更新时间:2023-12-02 11:24:33 25 4
gpt4 key购买 nike

Enumeration java的接口(interface)有2个方法

  1. hasNext()
  2. 下一个()

为什么不Iterator扩展枚举并添加删除方法()?

此外,如果我只想循环遍历我的集合,我可以使用枚举(或迭代器,如果它扩展枚举),因为循环语句只需要枚举。我不必担心集合被修改

最佳答案

Why doesn't Iterator extend Enumeration and add the remove() method?

来自documentation :

Iterator takes the place of Enumeration in the Java Collections Framework. Iterators differ from enumerations in two ways:

  • Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
  • Method names have been improved.

我怀疑后者是引入全新界面而不是扩展现有界面的真正原因。

Also, if all I want to do is loop over my collection, I can make do with an Enumeration (or an iterator if it extends enumeration) as loop statements only need an enumeration. I don't have to worry about the collection getting modified

好吧,如果您不想修改集合,那么就不要调用remove()。如果你真的非常不相信自己,你可以使用Collections.unmodifiableCollection()等创建一个只读包装器。

最后,值得注意的是,如果您使用 for-each 循环来迭代集合,则无论如何您都无法访问 remove() 方法:

for (String s : str_list) {
...
}

在这里,我们使用Iterator接口(interface),但无权访问实际的迭代器对象。

关于java - 为什么java中的集合没有只读迭代器的概念?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15244762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com