LinkedHashMaps 与 LinkedHashSets 的优缺点是什么?
有人可以解释选择其中一种的主要好处以及这种选择带来的危害吗?
Could someone explain the main benefits for choosing one over the other and the detriments that come with that choice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
它们解决不同的问题,LinkedHashMap 执行键到值的映射,LinkedHashSet 只是存储不重复的事物的集合。
链接哈希映射用于映射键/值对 - 例如,存储名称和年龄:
另一方面,链接哈希集用于存储一个事物的集合 - 名称,例如:
They solve different problems, LinkedHashMap does a mapping of keys to values, a LinkedHashSet simply stores a collection of things with no duplicates.
A linked hash map is for mapping key/value pairs -- for example, storing names and ages:
On the other hand, a linked hash set is for storing a collection of one thing -- names, for example:
LinkedHashSet 内部包含一个双向链表,贯穿其所有条目,定义元素的顺序。
此类允许 null 元素。
此类实现不同步,因此必须在外部进行同步。
LinkedHashMap 也不同步,必须在外部同步
例如:
除此之外,LinkedHashSet 存储每个元素的单个值,LinkedHashMap 存储键/值对。
在下图中,您可以看到 java.util.Collections。 实心框显示具体的类实现
替代文本 http://www.softfinity.com/diag1.png
LinkedHashSet internally contain a doubly-linked list running through all of its entries that defines the order of elements.
This class permits null elements.
This class implementation is not synchronized, so it must be synchronized externally.
LinkedHashMap is not synchronized either and must be synchronized externally
For example:
Other than that LinkedHashSet stores single values per element and LinkedHashMap stores key/value pair.
In the diagram below you can see java.util.Collections. Solid boxes show concrete class implementation
alt text http://www.softfinity.com/diag1.png
Set 只有值,不能放入重复项。Map 有键/值对。 它们有不同的用途。
集合将用作集合,传递一组对象,而当您有唯一的键来标识每个元素并且您希望能够通过该键访问它时,映射非常有用。
A Set has just values, you cannot put duplicates in. a Map has a key/value pair. They have different uses.
A set will get used as a collection, passing in a group of objects, whereas a map is useful for when you have a unique key to identify each element and you want to be able to access it by that key.
一个是一套,一个是地图。 为给定场景选择正确的数据结构。
One's a set, and one's a map. Choose the correct data structure for a given scenario.
LinkedHashMap
和LinkedHashSet
只有一个区别,那就是HashMap
和HashSet
的区别,即它们的父级。 同样,HashSet
只是HashMap
的变体。 您可以将HashSet
称为HashMap
,其中所有值都指向单个最终对象。 因此,它们两者不会给您带来太大差异。使用
LinkedHashSet
,除了密钥之外,您只能使用一个最终对象。使用
LinkedHashMap
,如果将所有键的值设置为 null,那么它也比 LinkedHashSet 用于 Set 目的更好。LinkedHashMap
andLinkedHashSet
has only one difference and that comes byHashMap
andHashSet
difference, their parents. Again,HashSet
is just a variation ofHashMap
. You can sayHashSet
as aHashMap
with all values pointing to a single final object. Therefore, both of them does not give you much differences.Using
LinkedHashSet
, You shall be using only one final object other than your keys.Using
LinkedHashMap
, if you set values as null for all keys, then its better than LinkedHashSet for Set purpose as well.