Java Container Chapter

Source: Internet
Author: User
Tags serialization concurrentmodificationexception

Container
A collection of-collection storage objects; Map table for storing key-value pairs
-iterator (iterator mode)
-collection accessor, which iterates through the objects in the collection
-All container classes that implement the collection interface have a iterator method that returns an object that implements the iterator interface. The iterator object is called an iterator, and the iterator interface method iterates through each element of the collection iteratively, and can remove the appropriate element from the collection
-collection
-set (features: unordered and non-repeatable)
-treeset: Based on a red-black tree, supports ordered operations, such as the operation of finding elements based on a range. But the lookup efficiency is not as hashset,hashset as the time complexity of the lookup is O (1), and TreeSet is O (logn).
-hashset: Based on hash table implementations, supports fast lookups, but does not support ordered operations. and the insertion order information of the element is lost, which means that the results obtained by using Iterator traversal HashSet are indeterminate.
-linkedhashset: Has HashSet lookup efficiency, and internally uses a doubly linked list to maintain the insertion order of elements
-Red and Black tree: Comics to read red and black tree Links: https://www.sohu.com/a/201923614_466939
-list (characteristic: ordered and repeatable)
-arraylist: Based on dynamic array implementation, support random access.
-Overview
-Randomaccess interface is implemented, so random access is supported. This is for granted, because ArrayList is implemented based on an array whose default size is 10.
-Serialization
-based on the array implementation, and has the dynamic expansion characteristics, so the array of saving elements will not necessarily be used, then there is no need to sequence all
Transient object[] A; Transient keyword declaration array is not serialized by default
-Why is the definition of a array to be decorated with the transient keyword so that it is not serialized by default?
If there are actually 5 elements, and the size of Elementdata is probably 10, then only 5 elements must be stored in the serialization, and the last five elements in the array are meaningless and do not need to be stored. So the designer of ArrayList designed the Elementdata to be transient, then serialized it manually in the WriteObject method, and serialized only those elements that were actually stored, not the entire array.
-You need to use ObjectOutputStream's WriteObject () to convert the object to a byte stream and output it when serializing. The WriteObject () method will reflect the invocation of the object's WriteObject () when the object is present WriteObject () to enable serialization. Deserialization uses the ObjectInputStream ReadObject () method, which is similar in principle.
The purpose of serialization in-java:
-Persistence of custom objects in some form of storage;
-Transfer objects from one place to another.
-More maintenance of the program
-Expansion
-Use the Ensurecapacityinternal () method when adding elements to ensure sufficient capacity, if not enough, you need to use the Grow () method to expand the size of the new capacity of Oldcapacity + (oldcapacity >> 1), That's 1.5 times times the old capacity.
-scaling operation requires calling arrays.copyof () to copy the original array to the new array, which is expensive, so it is best to specify the approximate capacity size when creating the ArrayList object and reduce the number of expansion operations
-delete Element
-You need to call System.arraycopy () to copy the elements that follow index+1 to the index position, the time complexity of the operation is O (N), and the cost of deleting the element is very high. ArrayList
-fail-fast
-modcount is used to record the number of times the ArrayList structure has changed. A change in structure means all operations that add or remove at least one element, or the size of an internal array, except that the value of the set element does not change the structure
-In the case of serialization or iteration, it is necessary to compare whether the modcount is changed before and after the operation, and if it changes the need to throw concurrentmodificationexception.
-fail-fast and Fail-Safe
-fail-fast
-fail-fast mechanism when traversing a set, when the collection structure is modified, it throws concurrentmodificationexception.
The collection classes under the-java.util package are fast-failing and cannot be modified in parallel under multiple threads (iterative process).
-fail-safe
-fail-safe any modifications to the collection structure are modified on a replicated collection, not as Fail-fast on the original set, and therefore not thrown concurrentmodificationexception
The containers under the-java.util.concurrent package are security failures that can be used concurrently in multiple threads and concurrently modified.
-Advantages
-Avoids the concurrentmodificationexception
-Cons
-the collection needs to be copied, resulting in a large number of invalid objects, overhead
-The data being read is not guaranteed to be the data in the current raw data structure.
-Iterators do not have access to the modified content, that is, the iterator iterates through the collection copy that was taken at the moment of the traversal, and the modified iterator that occurred during the iteration was unknown.
-vector: Similar to ArrayList, but it is thread-safe.
-its implementation is similar to ArrayList, but is synchronized using synchronized. So it's thread safe.
-Comparison with ArrayList
The-vector is synchronous, so the overhead is greater than the ArrayList and the access speed is slower. It is best to use ArrayList instead of vectors, because synchronization can be controlled entirely by the programmer himself;
-vector requests twice times its size per capacity, while ArrayList is 1.5 times times larger.
-linkedlist: Based on the two-way linked list implementation, only sequential access, but can quickly insert and delete elements in the middle of the list. Not only that, LinkedList can also be used as stacks, queues, and bidirectional queues.
-Overview
-based on the bidirectional linked list implementation, node is used to store the linked list nodes information.
private Static Class Node<e> {
E item;
Node<e> Next;
Node<e> prev;
}
Each linked list stores first and last pointers
Transient node<e> first;
Transient node<e> last;
-Comparison with ArrayList
-arraylist based on dynamic array implementation, LinkedList is based on two-way linked list;
-arraylist support random access, linkedlist not supported;
-linkedlist Add delete elements at any location faster.
-map
-treemap: Based on red-black tree implementation
-hashmap: Based on hash table implementation.
-Storage structure
-an array of type Entry is included inside the table.
Transient entry[] table;
Entry stores key-value pairs. It contains four fields, from the next field we can see that Entry is a linked list. That is, each position in the array is treated as a bucket, and a bucket holds a list. HashMap uses a zipper method to resolve conflicts, and the same list contains Entry with the same hash value.
{{{{{{{{{entry}}}}}}
-How the Zipper method works
hashmap<string, string> map = new hashmap<> ();
Map.put ("K1", "V1");
Map.put ("K2", "V2");
Map.put ("K3", "V3");
Create a new HASHMAP with a default size of 16;
Insert <K1,V1> key value pairs, first calculate K1 hashcode is 115, use the remainder method to get the bucket subscript 115%16=3.
Insert <K2,V2> key value pairs, first calculate K2 hashcode is 118, use the remainder method to get the bucket subscript 118%16=6.
Insert <K3,V3> key value pairs, first calculate K3 hashcode is 118, using the remainder method to get the bucket subscript 118%16=6, inserted in front of <K2,V2>.

-It should be noted that the insertion of the list is done in the head interpolation method, for example, the above <K3,V3> is not inserted in the back of <K2,V2>, but in the head of the linked list.
-the lookup needs to be divided into two steps:
-Calculates the bucket where the key value pairs are located;
-sequential lookups on linked lists, with time complexity clearly proportional to the length of the linked list.
-put operation
-hashmap allows the insertion of key-value pairs with a null key. However, because the null hashcode () method cannot be called, there is no way to determine the bucket subscript for the key-value pair, only by forcing a bucket subscript to be stored. The HASHMAP uses the No. 0 bucket to store key-value pairs with a null key.
-Determination of the barrel subscript
-Expansion
-Fundamentals
-Recalculate the barrel subscript
-Calculate Array capacity
-linked list to red black tree
-Starting with JDK 1.8, a bucket is stored with a list length greater than 8 to convert the linked list to a red-black tree
-Comparison with HashTable
The HashTable uses synchronized to synchronize.
HashMap can insert a Entry with a key of NULL.
The HashMap iterator is a fail-fast iterator.
HASHMAP cannot guarantee that the order of elements in the MAP will be constant over time.
-hashtable: Similar to HashMap, but it is thread-safe, which means that multiple threads at the same time can write to HashTable at the same time and do not result in inconsistent data. It is a legacy class and should not be used. It is now possible to use CONCURRENTHASHMAP to support thread safety, and concurrenthashmap is more efficient because Concurrenthashmap introduces a segmented lock.
-linkedhashmap: Use a doubly linked list to maintain the order of elements in order of insertion or least recently used (LRU) order.

Java Container Chapter

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.