简体   繁体   中英

what's the difference between HashSet and LinkedHashSet

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM