What is the main difference between Hashset, Treeset and LinkedHashset, Hashmap and how does it work in Java?

后端 未结 4 1612
余生分开走
余生分开走 2020-12-20 01:50

I just understand that LinkedHashSet does not allows duplicate elements when it is inserting. But, I dont understand how does Hashset works in Hava? I know a bit that Hashta

4条回答
  •  情话喂你
    2020-12-20 02:25

    First of all, you need to know that all Set implementations share the same feature: they don't allow duplicates. It's not just a feature of the LinkedHashSet.

    Second, one important difference is that, out of the 3 set types you asked about, the TreeSet is a sorted set, that is elements are ordered according to their natural ordering or according to a logic described imperatively using a Comparator or implementing the Comparable interface.

    Switching to the difference between HashSet and LinkedHashSet, please note that LinkedHashSet is a subclass of HashSet. They are not sorted sets.

    HashSet is the fastest implementation of a set and it ensures the uniqueness of elements using (first) their hash value returned by the hashCode() method and (then) their equals() method. Behind the scenes, it uses a HashMap.

    The LinkedHashSet ensures consistent ordering over the elements of the set with the help of a LinkedList, which basic HashSets do not provide.

提交回复
热议问题