Home > Java > javaTutorial > body text

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

高洛峰
Release: 2017-01-22 15:25:03
Original
1864 people have browsed it

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!