what's the difference between HashSet and LinkedHashSet

℡╲_俬逩灬. 提交于 2019-12-11 04:43:00

问题


I saw that LinkedHashSet extends HashSet and I know it preserves order.
However, from checking the code in the JDK it seems that LinkedHashSet contains only constuctor and no implementation, so I guess all the logic happens in HashSet?
If that is correct, why is it designed like that? it seems very confusing.

EDIT: there was an unfortunate mistake in the question. I wrote HashMap and LinkedHashMap instead of HashSet and LinkedHashSet. I fixed the question answer it if possible.
Also, I was interested why Java designers chose to implement it like that.


回答1:


Yes, LinkedHashMap calls its super constructor. One thing it does is to override the init() method, which is called by the super constructor.

The LinkedHashMap is an HashMap with a doubly-linked list implementation added.




回答2:


As you said the difference between the two data structures is that the LinkedHashMap is an HashMap that preserve the insertion order of pairs.

So the Linked one is intended to used as an HashMap via standard methods of the HashMap and the only method added is removeEldestEntry(), useful if you want to deal with the "list" part of the data structure.



来源:https://stackoverflow.com/questions/10681360/whats-the-difference-between-hashset-and-linkedhashset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!