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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:01:12  来源:igfitidea点击:

Reason HashMap does not implement Iterable interface?

javacollections

提问by Amar

Can anybody tell me the reason why HashMapdoesn't implement the Iterableinterface?

谁能告诉我为什么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

Map doesn't implement it but you can use keySet()or values()or entrySet()and all implement iterator as they are sets. See Map javadoc here

Map 没有实现它,但您可以使用keySet()orvalues()entrySet()和所有实现迭代器,因为它们是集合。在此处查看地图 javadoc

回答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, Mapin general (and HashMapin particular) do not implement Iteratorbecause 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 接口,因为它不包含元素,而是包含键及其对应值的条目。