The difference between ArrayList and LinkedList (super detailed and easy to understand)


1. The difference between ArrayList and LinkedList queries

  • LinkedList is implemented based on a linked list and is suitable for insertion.
  • ArrayList is implemented based on arrays and is suitable for queries.

Advantages of ArrayList : For ArrayList, its real advantage is to query elements by subscript. Compared with LinkedList, LinkedList can also query elements by subscript, but LinkedList needs to traverse the underlying linked list to find the element with the specified subscript, while ArrayList No, specify the subscript to query, ArrayList is better than LinkedList, so this is the advantage of ArrayList.

However, if we are talking about getting the first element or the last element, there is no difference in performance between ArrayList and LinkedList, because there are two properties in LinkedList that record the head node and tail node in the current linked list respectively. , does not need to traverse the linked list.

The above is the difference between ArrayList and LinkedList in terms of query

Second, the difference between ArrayList and LinkedList insertion

The addition operation of ArrayList is subject to capacity expansion, and the addition operation of ArrayList should be considered on a case-by-case basis.

  • Add elements at the last position, no need to move, need to expand
  • Add an element at the specified position, the element at the specified position and the elements behind it all move backward; the efficiency is relatively slow. (Because the position is specified, there is no need to traverse the search, but the element needs to be moved)
  • It can be inserted at the specified subscript position or the end of the array. This kind of insertion is usually very fast, but if an insertion operation triggers expansion, then this insertion will add additional expansion costs.

There is no expansion in the addition operation of LinkedList .

  • If it is inserted at the head or tail of the linked list, it is very fast, because LinkedList has a separate attribute record for the head node and tail node of the linked list. However, if it is inserted at the specified subscript position, then you need Traversing the linked list to find the specified location reduces efficiency.

3. Summary

Use ArrayList in the following situations

  • A certain element in the list is frequently accessed.
  • It is only necessary to add and remove elements at the end of the list.

Use LinkedList in the following situations

  • You need to iterate through a loop to access certain elements of the list.
  • It is necessary to frequently add and delete elements at the beginning, middle, and end of the list.
  • Do double-ended queue use

Guess you like

Origin blog.csdn.net/weixin_54040016/article/details/127946278