Let's take a look at the inheritance diagram for some of the main containers in Java:
Then we analyze the data structure and some implementations of the above-mentioned containers:
1. ArrayList (non-thread safe)
The underlying data structure is actually an array, but it is better than the array is that he is dynamic, that is, do not have to be like an array of fixed size, then how he implemented this data structure is an array, but give us look really not fixed size?
ArrayList is to handle the growth of arrays by copying the underlying Object array (the System.arraycopy method);
When the capacity of the ArrayList is insufficient, it expands capacity by expanding the capacity to 1.5 times times the current capacity and, if not enough, expanding the capacity to the quantity currently required.
So it can be seen from above that ArrayList is used to find the equivalent of a very fast array, but it is very slow if it is inserted or deleted.
2. LinkedList (non-thread safe)
As the name implies that the underlying data structure is a linked list, and is a doubly linked list, so he also has the characteristics of the list, that is, insert or delete the words quickly, but if the search is relatively slow.
3.HashSet (non-thread safe)
The underlying data structure is a hash table (see below for a hash table), only the object is stored (and HashMap is the store key value pair), the prominent feature is that the object is not repeatable, to ensure that this is through the first comparison of each object's hashcode, if hashcode the same, then compare equal () To determine if two objects are duplicated, so the objects placed in HashSet must be rewritten hashcode () and equal ().
4.HsahMap (non-thread safe)
The bottom is also a hash table (see below), which stores the data by key-value pairs, gets the value by key, is faster than HashSet, and the key and value can be null.
Now let's introduce the hash table (hash table) data structure:
First, each object produces a hash value (because the hash value is too large, the array can not open so large, it will cause a huge waste), so a hash function needs to be converted to a hash value, 1000 into a 0,,3013 3, so that access to the object is as easy as the array, inserting objects is also very convenient, If it is the same value after the conversion of the hash values, that is, a conflict, as the above resolution of the conflict is the way the list, the hash value in the same position in the array is linked with a chain. So the hash table is actually looking fast, and the insertion and deletion is fast, which solves some of the shortcomings of the array and the linked list.
Data structure analysis of some containers in Java