Java HashSet 键/值对
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2504080/
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
Java HashSet key/value pair
提问by harley
Why doesn't Java provide functions to get the key/value pairs in a HashSetlike exists in Hashtable? It seems like a real pain to have to iterate over it every time you need to get at something. Or is there an easier way to do this?
为什么 Java 不提供函数来获取HashSet类似中的键/值对Hashtable?每次你需要得到一些东西时都不得不迭代它似乎是一种真正的痛苦。或者有没有更简单的方法来做到这一点?
回答by brabster
HashSetdoesn't have key/value pairs. It is a Setof objects and you would use an implementer of Set to ensure that a collection of objects contained no duplicates.
HashSet没有键/值对。它是一组对象,您将使用 Set 的实现者来确保对象集合不包含重复项。
Implementers of Map like HashMaphave key/value pairs and provide a get(Object key)method to get the value associated with a key.
像HashMap这样的 Map 实现者有键/值对,并提供一个get(Object key)方法来获取与键关联的值。
回答by Joachim Sauer
Since a Setdoesn't contain keys and values, there is no way such a view could be provided.
由于 aSet不包含键和值,因此无法提供这样的视图。
What would you consider to be the key and what would be the value in a Set?
你认为什么是关键,a 中的价值是Set什么?
回答by Progman
A Setdon't have any key/value pairs, just (unique) values. As you already said you get these values via the Iteratoror by returning an array with these values with the toArray()method.
ASet没有任何键/值对,只有(唯一的)值。正如您已经说过的,您可以通过Iterator或 通过使用该toArray()方法返回具有这些值的数组来获取这些值。
Maybe you are looking for a Listinstead.
也许你正在寻找一个List替代。

