Java container study notes summary List

List interface

Insert picture description here
The list interface stipulates that the elements stored in the container are ordered and can be repeated.
The implementation classes that implement it are mainly ArrayList and LinkedList, as well as the almost useless Vector

ArrayList

Internal realization

  • First of all, the internal is implemented with an array , an Object array named elementData
  • When creating an ArrayList without parameters, the initial assignment is an empty array , and capacity will be allocated only when elements are actually added.
    (That is, when adding the first element to the array, the array capacity is expanded to 10)

Expansion The expansion of the
container has always been the focus
. The expansion of the ArrayList is placed in the logic of the add method, that is, when you add elements, you only care about the expansion.

添加元素(add):
	判断扩容(ensureCapacityInternal)://确保容量够,不会越界
		如果当前数组是空数组://刚刚创建,尚未添加元素
			预期容量改为10 //当存储元素时,至少是要有10个大小的容量的
		否则预期容量是当前size+1
		尝试扩容(ensureExplicitCapacity):
			如果预期容量大于现在数组的大小:
				扩容1.5倍(grow)//近似,位运算
	添加元素

The above is a summary of the logic of adding elements to the add method. Before adding elements, you need to judge whether the current capacity is enough, and if it is not enough, you need to expand the capacity.


grow method

  • The specific expansion operation is the grow method, where bit operations are used
  • If it grows, the expected capacity will be passed in, and it will be 1.5 times the maximum size of the previous capacity and the expected capacity (1 starts to hit the expected capacity, and later is 1.5 times, this is also well understood)
  • If the expected capacity is greater than MAX_ARRAY_SIZE, the capacity is positioned Integer.MAX_VALUE (MAX·· is a constant value)

During expansion, the Arrays.copyOf() method is called, which creates a new array internally, and then calls the System.arraycopy() method to copy the contents of the old array to the new array. So as to realize the expansion operation.

And System.arraycopy () method, in fact the function is to copy a part of the portion of the array to another array (which may be all)
like for comparison: the former because the new array, more suitable for expansion
which is generally from Copy to yourself, so it is more suitable for moving, such as insert (add(xxx, index)) which needs to be moved


Active expansion is
due to 1.5 times expansion (can be understood as 0-10-15-22.5-···the following group is from 1.5). With this mechanism, if the user needs a large amount of storage, the expansion will be performed many times, and each time is required It takes O(n) time to copy the array, which is inefficient.
Therefore, ArrayList also provides a method for users to specify the size of the capacity to expand, thereby reducing the number of expansions.
ensureCapacity


When deleting the specified element, the same is true. You need to call the System.arraycopy() method, and then move the element starting at index+1 to the index. The time complexity is O(n)


Serialization
Because the length of the array inside the ArrayList is basically larger than the size of the actual number of stored elements, there is no need to serialize the internal array as an implementation when serializing, so the elementData is modified with transient.
And also wrote the writeObject method and readObject method to serialize only the part of the array filled with elements.


Fail-Fast
ArrayList uses the modCount variable to record the number of times the ArrayList structure has changed: add or delete or adjust the size of the array (only modifying the element value does not count, but the structure needs to be modified)

The
fail-fast mechanism is mainly used for multi-threaded concurrency security issues here. The fail-fast mechanism is an error mechanism in the java collection. When multiple threads operate on the contents of the same collection, a fail-fast event may occur. For example: when a thread A traverses a collection through iterator, if the content of the collection is changed by other threads; then when thread A accesses the collection, a ConcurrentModificationException will be thrown and a fail-fast event will be generated. (From Baidu Encyclopedia)
During concurrent iteration, judge, if modcount is modified, it can be terminated directly,

This variable was modified by volatile before, but now jdk1.7 has been removed, because I think you can use concurrent packages for concurrency, this is still reserved for single-threaded use.

LInkedList

As a commonly used List implementation class, it is used a lot.

  • Implemented List interface and Deque interface
  • Double-ended linked list

The following is some of its simple method logic

add method: add nodes to the tail

  • add://添加节点到尾部
    	linkLast://将节点加到尾部,此处需要判空
    

add(int index, E e): add a node to the specified position

  • add(int index, E e):
    	如果是尾部(用长度和index来判断),linkLast
    	不是尾部,找到要插入的点(O(n)遍历到指定位置)
    	将其和输入传给linkBefore:
    		进行插入
    

addAll: insert the collection to the end of the linked list

  • 1.检查index范围是否在size之内
    2.toArray()方法把集合的数据存到对象数组中
    3.得到插入位置的前驱和后继节点
    4.遍历数据,将数据插入到指定位置
    

addFirst: add a node to the head

  • The linkFirst method is called, the operation is very simple, there is nothing to say

addLast: the same

get(int index): Get the node at the specified position

  • This is to call the node method

indexOf(Object o): Obtain the index according to the object

  • Traverse from the beginning to find the index

lastIndexOf:

  • Traverse from the end to find the index

contains(Object o): Check whether the object is in the linked list

  • Use index to judge

On the whole, LinkedList is relatively simple, and the difference between it and ArrayList is also obvious
. The underlying implementation is different, whether it has efficient random access capability, whether it has efficient insertion capability, storage efficiency, etc. These things are all comparisons. Simple, I won’t go into details

Vector

I won't elaborate on this. It's similar to ArrayList. It is also realized by Object array, and a lot of Synchronized keywords are used in it, so it can meet the security problem of multi-threading. But the performance is therefore average.
Generally don't use it

Guess you like

Origin blog.csdn.net/qq_34687559/article/details/114385916