Introduction to the relationship and difference between Set and List in Java

  • 2020-04-01 03:45:41
  • OfStack

Both interfaces are inherited from the Collection.

The List (inteface)

Order is the most important feature of a List, which ensures that a specific order of elements is maintained.
--ArrayList allows fast random access to elements.
- LinkedList optimize the sequential access, to insert and remove the overhead of among the List is not large, with addFrist (), addLast (), getFirst, getLast, removeFirst and removeLast (). These methods make LinkedList as the stack/queue/two-way queue.

Set (inteface)

Each element stored in a Set must be unique and there is no guarantee that the order of the elements will be maintained
-- a Set designed for quick lookups, where the HashSet object must have a hashCode() defined.
- TreeSet  Protect the Set of the order, which can be used to extract the ordered sequence from the Set.
LinkedHashSet has the query speed of a HashSet and internally USES linked lists to maintain the order of elements.

They are stored differently:

TreeSet USES the tree data structure of red-black trees to sort elements.
HashSet takes the hash function, which is specifically designed for quick queries.
Hash is used internally on LinkedHashSet to speed up queries, while linked lists are used to maintain the order of elements.

When using HashSet/TreeSet, you must define equals() for the class. While HashCode() is for HashSet, as a programming style, HashCode() should be overwritten when equals() is overwritten.


Related articles: