Java HashMap 没有实现 Iterable 接口的原因?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19422365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reason HashMap does not implement Iterable interface?
提问by Amar
Can anybody tell me the reason why HashMap
doesn't implement the Iterable
interface?
谁能告诉我为什么HashMap
不实现Iterable
接口的原因?
回答by user987339
Hash map contains two data structures, keys and values, and each of them has an iterator. HashMap as a whole is not a data structure that you should iterate over.
哈希映射包含两个数据结构,键和值,每个都有一个迭代器。HashMap 整体上不是您应该迭代的数据结构。
回答by Manoj
回答by Admit
Not directly. You need a 1 dimension structure to iterate it.
不直接。您需要一个一维结构来迭代它。
hashMap.entrySet().iterator()
will do the job.
hashMap.entrySet().iterator()
会做的工作。
回答by dasblinkenlight
To be blunt, Map
in general (and HashMap
in particular) do not implement Iterator
because it is not clear what it should be iterating. There are three choices:
坦率地说,Map
一般(HashMap
特别是)不要实现,Iterator
因为不清楚它应该迭代什么。有以下三种选择:
- Keys
- Values
- Entries
- 钥匙
- 价值观
- 参赛作品
None of the three choices above look entirely unreasonable: an argument can be made in favor of each of these approaches. In the end, the library designers decided not to make this choice for you, letting programmers pick what to iterate explicitly.
上述三种选择中没有一种看起来完全不合理:可以对这些方法中的每一种进行论证。最后,库设计者决定不为您做这个选择,让程序员选择显式迭代的内容。
回答by code_fish
Sun could have made Map extend Iterable, but that would require that Map itself should have an iterator() method. Imagine all the custom Map implementations that would be broken. It's bad enough they did that with the java.sql interfaces.
Sun 可以让 Map 扩展 Iterable,但这需要 Map 本身应该有一个 iterator() 方法。想象一下所有会被破坏的自定义 Map 实现。他们用 java.sql 接口做到了这一点已经够糟糕了。
Besides, you can iterate over the map by using keySet(), entrySet() or values() - that's 8, 10 or 8 extra characters.
此外,您可以使用 keySet()、entrySet() 或 values() 遍历映射 - 即 8、10 或 8 个额外字符。
回答by code_fish
Map interface does not implement Collection interface, because it does not contain elements but contains entries of keys and their corresponding values.
Map 接口没有实现 Collection 接口,因为它不包含元素,而是包含键及其对应值的条目。