Home  >  Article  >  Java  >  Introduction to the relationship and difference between Set and List in Java

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

高洛峰
高洛峰Original
2017-01-22 15:25:031897browse

Both interfaces are inherited from Collection.

List (inteface)

Order is the most important feature of List, which ensures that the specific order of elements is maintained.
-ArrayList Allows fast random access to elements.
——LinkedList optimizes sequential access. The cost of inserting and removing from the middle of the List is not large. It has addFrist(), addLast(), getFirst, getLast, removeFirst and removeLast(). .These methods allow LinkedList to be used as a stack/queue/bidirectional queue.

Set (inteface)

Each element stored in Set must be unique, and the order of the elements is not guaranteed to be maintained. Add to Set The Object must define the equals() method
--HashSet A Set designed for fast search, and the HashSet object stored must define hashCode().
--TreeSet A Set that protects the order, which can be used to extract from the Set Ordered sequence.
-LinkedHashSet Has the query speed of HashSet, and internally uses a linked list to maintain the order of elements.

The storage methods between them are different:

TreeSet uses red and black The elements are sorted according to the tree structure.
HashSet uses a hash function, which is specially designed for fast query.
LinkedHashSet uses hash internally to speed up query, while using a linked list to maintain the order of elements.

When using HashSet/TreeSet, equals() must be defined for the class; HashCode() is for HashSet. As a programming style, when equals() is overridden, hashCode() should also be overridden.

For more related articles on the relationship and differences between Set and List in Java, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn