Collection of Java Collection frameworks and javacollection

Source: Internet
Author: User
Tags addall concurrentmodificationexception

Collection of Java Collection frameworks and javacollection
This figure is a class diagram of the relationship between Collection-related interfaces and classes in java. Among them, the class is only part of the set framework, a more common part. It was really hard to draw a class chart for the first time, but the harvest was not small. The following describes the related interfaces and classes. The text is from the jdk api 1.6 Chinese version. Forgive me for being lazy. I really don't want to write it myself. It's too troublesome. If any error occurs, please correct it. , Set, Queue, and List Interfaces All inherit from the Collection interface.

AbstractCollection <E>

This class provides the backbone implementation of the Collection interface to minimize the work required to implement this interface.

To implement an unchangeable collection, programmers only need to extend this class and provide implementation of the iterator and size methods. (The iterator returned by the iterator method must implement hasNext and next .)

To implement a modifiable collection, the programmer must overwrite the add method (otherwise, UnsupportedOperationException will be thrown). The iterator returned by the iterator method must also implement its remove method.

According to the recommendations in the Collection interface specification, programmers should generally provide a void (No parameter) and Collection constructor.

 

SetA collection that does not contain repeated elements. More specifically, set does not contain e1 and e2 elements that meet e1.equals (e2), and contains at most one null element. Note: If you use a mutable object as a set element, you must be extremely careful. If the object is an element in the set and the value of the object is changed in a way that affects the comparison of equals, the set action is uncertain. A special case of this prohibition is that a set cannot contain itself as an element. HashSetThis Set interface is supported by a hash table (actually a HashMap instance. It does not guarantee the set iteration sequence; in particular, it does not ensure that the sequence remains unchanged. This class allows the use of null elements. This class provides stable performance for basic operations, including add, remove, contains, and size, assuming that the hash function correctly distributes these elements in the bucket. The time required for iteration on this set is the "capacity" and proportion of the size (number of elements) of the HashSet instance and the number of underlying HashMap instances (number of buckets. Therefore, if iteration performance is important, do not set the initial capacity too high (or set the loading factor too low ). Note, This implementation is not synchronous.If multiple threads access a hash set at the same time, and at least one thread modifies the set, it must maintain external synchronization. This is usually done by performing synchronization operations on the objects that encapsulate the set. If such an object does not exist, use the Collections. synchronizedSet method to "Wrap" the set. It is best to complete this operation at creation to prevent unexpected non-synchronous access to the set:
  Set s = Collections.synchronizedSet(new HashSet(...));
Note: The Fast failure behavior of the iterator cannot be guaranteed, because in general, it is impossible to make any hard guarantee for non-synchronous concurrent modifications. The quick failure iterator tries its best to throw ConcurrentModificationException. Therefore, writing a program dependent on this exception to improve the correctness of such iterators is an incorrect practice: the fast failure behavior of the iterator should only be used to detect bugs. LinkedHashSetImplement the hash table and link list of the Set interface with predictable iteration sequence. This implementation differs from HashSet in that the latter maintains a list of dual links running on all entries. The Link List defines the iteration order, that is, the iteration is performed based on the order (insertion order) in which the elements are inserted into the set. Note that the insertion sequence is not affected by the elements re-inserted in the set. (If you call s. add (e) Immediately after s. contains (e) returns true, Element e is re-inserted into set s .) This class provides all optional Set operations and allows null elements. Like HashSet, it can provide stable performance for basic operations (add, contains, and remove), assuming that the hash function correctly distributes elements to the bucket. Because the cost for maintaining the link list is increased, its performance is likely to be slightly inferior to that of HashSet. However, this exception is that the time required for the LinkedHashSet iteration is proportional to the set size, not the capacity. HashSet iterations are likely to spend a lot because the iteration time required is proportional to its capacity. The linked hash set has two parameters that affect its performance: initial capacity and loading factor. They are very similar to the definitions in HashSet. Note that selecting a very high value for the initial capacity has less impact on this type than HashSet, because the iteration time of this type is not affected by the capacity. Note, This implementation is not synchronous.If multiple threads access a hash set at the same time, and at least one thread modifies the set, it must maintain external synchronization. This is usually done by performing synchronization operations on the objects that encapsulate the set. If such an object does not exist, use the Collections. synchronizedSet method to "Wrap" the set. It is best to complete this operation at creation to prevent unexpected non-synchronous access to the set:
  Set s = Collections.synchronizedSet(new LinkedHashSet(...));
Note: The Fast failure behavior of the iterator cannot be guaranteed. In general, when there are non-synchronous concurrent modifications, it is impossible to make any powerful guarantee. The quick failure iterator tries its best to throw ConcurrentModificationException. Therefore, writing a program dependent on this exception is incorrect. The correct practice is that the fast failure behavior of the iterator should only be used to detect program errors. TreeSetImplement NavigableSet Based on TreeMap. Sort the elements in the natural order of the elements, or sort the elements based on the Comparator provided when the set is created, depending on the construction method used. This provides guaranteed log (n) time overhead for basic operations (add, remove, and contains. Note: to correctly implement the Set interface, the set maintenance sequence (whether or not an explicit comparator is provided) must be consistent with equals. (For precise definitions consistent with equals, see Comparable or Comparator .) This is because the Set interface is defined according to the equals operation, but the TreeSet instance uses its compareTo (or compare) method to compare all elements. Therefore, from the perspective of set, in this method, two equal elements are considered equal. Even if the set sequence is inconsistent with equals, its behavior is well defined. It only violates the conventional protocol of the Set interface. Note, This implementation is not synchronous.If multiple threads access a TreeSet at the same time, and at least one thread modifies the set, it must be synchronized externally. This is generally done by performing synchronization operations on the objects that naturally encapsulate the set. If such an object does not exist, use the Collections. synchronizedSortedSet method to "Wrap" the set. This operation is best performed during creation to prevent unexpected non-synchronous access to the set:
  Set s = Collections.synchronizedSet(new TreeSet(...));
Note: The Fast failure behavior of the iterator cannot be guaranteed. In general, when there are non-synchronous concurrent modifications, it is impossible to make any affirmative guarantee. The quick failure iterator tries its best to throw ConcurrentModificationException. Therefore, writing programs dependent on this exception is incorrect. The correct practice is that the fast failure behavior of the iterator should only be used to detect bugs. CopyOnWriteArraySetUse the internal CopyOnWriteArrayList Set for all its operations. Therefore, it shares the following basic attributes: 1. It is most suitable for applications with the following features: the set size is usually kept small, and the read-only operation is far more than the variable operation, it is necessary to prevent conflicts between threads during traversal. 2. it Thread-safe. 3. Because the entire basic array needs to be copied, variable operations (add, set, remove, and so on) are costly. 4. The iterator does not support variable remove operations. 5. It is fast to use the iterator for traversal and will not conflict with other threads. When constructing the iterator, The iterator depends on the unchanged array snapshot. ConcurrentSkipListSetA ConcurrentSkipListMap-based scalable concurrent NavigableSet implementation. The set elements can be sorted by their natural order, or by the Comparator provided when the set is created, depending on the construction method used. This provides the expected average log (n) time overhead for the contains, add, remove, and their variants. Multiple Threads can safely ConcurrencyPerform insert, remove, and access operations. The iterator is weak and consistent. The returned elements reflect the set status at the time when the iterator is created or after it is created. They do not throw ConcurrentModificationException and can concurrently process other operations. The ascending sort view and its iterator are faster than the descending sort view and its iterator. Note that, unlike most collections, the size method here is not a fixed time (constant-time) operation. Due to the asynchronous nature of these sets, determining the current number of elements requires traversing the elements. In addition, batch operations such as addAll, removeAll, retainAll, and containsAll cannot be performed in atomic mode (atomically. For example, the iterator that operates concurrently with the addAll operation can only view some additional elements. This class and its Iterator implement all the optional methods for the Set and Iterator interfaces. Like most other concurrent collection implementations, this class does not allow null elements, because it cannot reliably distinguish null parameters and return values from nonexistent elements. QueueThe collection used to save the elements before processing the elements. In addition to basic Collection operations, the queue also provides other insert, extract, and check operations. Each method has two forms: one is to throw an exception (when the operation fails), and the other is to return a special value (null or false, depending on the operation ). The latter form of the insert operation is specifically designed for the Capacity-limited Queue implementation. In most implementations, the insert operation will not fail. Generally (but not necessarily) queues sort each element in FIFO (first-in-first-out) mode. Except for the priority queue and the LIFO Queue (or stack), the former sorts the elements based on the provided comparator or the natural sequence of the elements, and the latter orders the elements based on the LIFO (later, first, first, and foremost) to sort the elements. No matter which sort method is used, the queue header is the elements removed by calling remove () or poll. In a FIFO queue, all new elements are inserted at the end of the queue. Other types of queues may use different element placement rules. Each Queue implementation must specify its sequential attribute. The Queue implementation usually does not allow the insertion of null elements, although some implementations (such as the Queue list) do not prohibit the insertion of null. Even if null is allowed, null should not be inserted into the Queue, because null is also used as a special return value of the poll method, indicating that the Queue does not contain elements. The Queue implementation usually does not define the element-based version of the equals and hashCode methods, but inherits the identity-based version from the Object class, because for Queues with the same elements but different sorting attributes, element-based equality is not always well defined. Concurrent1_queueA connection node-based unbounded thread security queue. This queue sorts the elements according to the FIFO principle. The queue header is the longest element in the queue. The tail of a queue is the minimum time element in the queue. Insert the new element to the end of the queue. The queue acquisition operation obtains the element from the queue header. When multiple threads share access to a public collection, concurrentincluqueue is an appropriate choice. The queue does not allow null elements. Memory consistency effect: when other concurrent collections exist, the Operation happen-before puts the object into the thread before concurrent1_queue and then accesses or removes this element from concurrent1_queue through another thread. ListAn ordered collection (also called a sequence ). Users of this interface can precisely control the insert position of each element in the list. You can access the element based on the integer index (position in the list) of the element and search for the element in the list. Unlike set, the list usually allows repeated elements. To be more precise, the list usually allows e1.equals (e2) elements to pair e1 and e2, and if the List itself permits null elements, they usually allow multiple null elements. It is inevitable that some people want to disable the duplicate list by throwing a running exception when the user tries to insert duplicate elements. But we hope that the less this usage, the better. Note: although the list allows itself to be included as an element, it is recommended that you be careful: on such a list, the equals and hashCode methods are no longer well defined. ArrayListThe implementation of Variable-size array of the List interface. All optional list operations are implemented, and all elements including null are allowed. In addition to the List interface, this class also provides some methods to internally store the size of the List array. (This is basically equivalent to the Vector class, except that this class is not synchronized .) The size, isEmpty, get, set, iterator, and listIterator operations are all run at a fixed time. The add operation runs at a scheduled time, that is, it takes O (n) Time to add n elements. All other operations are run in linear time (in general ). Compared with the constant factor used for the implementation of the sort list, the constant factor for this implementation is low. Each ArrayList instance has a capacity. This capacity refers to the size of the array used to store list elements. It is always equal to at least the size of the list. As elements are added to the ArrayList, their capacity increases automatically. The details of the growth policy are not specified, because it is not just as simple as adding an element to allocate a fixed time overhead. Before adding a large number of elements, the application can use the ensureCapacity operation to increase the capacity of the ArrayList instance. This can reduce the number of incremental redistribution. Note, This implementation is not synchronous. ShortlistList interface. Implement all optional list operations and allow all elements (including null ). In addition to the List interface, the revoke List class also provides a unified naming method for get, remove, and insert elements at the beginning and end of the List. These operations allow the link list to be used as a stack, queue, or dual-end queue. This type of Deque interface provides first-in-first-out queue operations for add and poll, as well as other stack and double-end queue operations. All operations are performed according to the dual-link list. The indexing operation in the list traverses the list from the beginning or end (from the end near the specified index ). Note, This implementation is not synchronous. CopyOnWriteArrayListA thread-safe variant of ArrayList. All variable operations (add, set, and so on) are implemented by performing a new copy on the underlying array. This usually requires a lot of overhead. However, when the number of traversal operations exceeds the number of variable operations, this method may be more effective than other alternative methods. It is also useful when you cannot or do not want to perform synchronous traversal, but you need to exclude conflicts from the concurrent threads. The Snapshot-style iterator method uses references to the array status when creating the iterator. This array does not change during the lifetime of the iterator, so conflicts cannot occur, and the iterator ensures that ConcurrentModificationException is not thrown. After an iterator is created, the iterator does not reflect the addition, removal, or modification of the list. The element change operations (remove, set, and add) on the iterator are not supported. These methods will throw UnsupportedOperationException. All elements, including null, are allowed. Memory consistency effect: when other concurrent collections exist, the Operation happen-before puts the object into the thread before CopyOnWriteArrayList and then accesses or removes the element from the CopyOnWriteArrayList through another thread. VectorThe Vector class can implement a scalable array of objects. Like an array, it contains components that can be accessed using integer indexes. However, the Vector size can be increased or reduced as needed to meet the needs of adding or removing items after the Vector is created. Each vector tries to optimize storage management by maintaining capacity and capacityIncrement. Capacity should always be at least the same size as the vector; this value is usually larger than the latter, because as the component is added to the vector, its storage will increase the storage block by the size of the capacityIncrement. The application can increase the vector capacity before inserting a large number of components. This reduces the amount of redistribution. StackThe Stack class indicates the object Stack of the last-in-first-out (LIFO. It extends the Vector class through five operations, allowing the Vector to be considered as a stack. It provides common push and pop operations, and the peek method for obtaining stack vertices, the empty method for testing whether the stack is empty, the search Method for Finding items in the stack and determining the distance to the top of the stack. It does not contain items when a stack is created for the first time. The Deque interface and its implementation provide a more complete and consistent set for LIFO stack operations. This set should be used first, rather than this type. For example:
  Deque<Integer> stack = new ArrayDeque<Integer>();

 

Related Article

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.