The container in Java can be said to be the most used class except string. Containers can be divided into two types, one is traversal, that is, inheriting the iterable interface, represented by list; the other is non-traversal, represented by map. Their relationships are as follows:
In this article, I will share with you my understanding of Java. util. List and its corresponding inheritance classes.
Linear table in Java
List is a linear table in the data structure. It has two implementation methods: arraylist and sort list, arraylist is convenient for random element access, while it is slow to insert and remove elements in the list center. The reverse is true for the partial list.
How arraylist and rule list work
- There are two main member variables in the arraylist (and one is serialversionuid, used for serialization), which are
private transient Object[] elementData; private int size;
Looking at these two fields, I believe you will be able to get a rough idea of how this class works. When arraylist is constructed without parameters, the default size of arraylist is 10. When the add () method is called later, if the size is not enough, a new object [] array is larger than the current object [] array, and then arrays is called. the copyof () method overwrites the original object [] array.
- In the member list, there are also two main member variables, and it also has a key internal class, as shown below:
private transient Entry<E> header = new Entry<E>(null, null, null); private transient int size = 0; private static class Entry<E> { E element; Entry<E> next; Entry<E> previous; Entry(E element, Entry<E> next, Entry<E> previous) { this.element = element; this.next = next; this.previous = previous; } }
I believe that when you see the code, you almost understood the working method of the tranquility list. Here, we will introduce how to add elements to the listing list first with the source code:
public boolean add(E e) {addBefore(e, header);return true; } private Entry<E> addBefore(E e, Entry<E> entry) {Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);newEntry.previous.next = newEntry;newEntry.next.previous = newEntry;size++;modCount++;return newEntry; }
The code may be unclear ,:
This is the whole process of adding elements to the tranquility list.
List internal class iterator
Different from map, collection can be traversed, while map can find the corresponding value based on the key.
In list, iterator is implemented through internal classes. Iterator we use only two methods, hasnext (), to determine whether it has the next value, and next () to obtain its next value. I believe you don't need to talk about these two methods. Another method is remove (), which will remove the previous element of the element you are traversing, when you call remove () When iteraotr does not start traversing elements, an exception is thrown.
Simple.