Collection of the Java collection framework

Source: Internet
Author: User
Tags addall sorts concurrentmodificationexception

This diagram is a class diagram of the relationship between Collection-related interfaces and classes in Java.  Where classes are just a part of the collection framework and are more commonly used.  The first time to draw a class diagram, it is very laborious, but the harvest is not small. The following is an explanation of the related interfaces and classes. The text comes from the JDK API 1.6 Chinese version. Forgive my laziness, really do not want to write their own, too troublesome.  If there is any mistake, please correct me. , the Set, Queue, and List interfaces inherit from the Collection interface.

  Abstractcollection<e>

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

To implement a non-modifiable collection, programmers simply extend this class and provide implementations 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 override this class's Add method (otherwise, it throws unsupportedoperationexception), and the iterator returned by the iterator method must implement its Remove method in addition.

As recommended in the Collection interface specification, programmers should typically provide a void (parameterless) and Collection construction method.

Set  A collection that does not contain duplicate elements.  More specifically, the set does not contain elements that satisfy e1.equals (E2) to E1 and E2, and contains a maximum of 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 set and changes the value of an object in a way that affects the equals comparison, then the behavior of the set is indeterminate. A special case of this prohibition is that a set is not allowed to contain itself as an element. HashSet  This class implements the Set interface, which is supported by a hash table (actually a HashMap instance). It does not guarantee the set's iteration order, especially it does not guarantee that the order is constant.   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 the elements in the bucket. The time it takes to iterate over this set is proportional to the size of the HashSet instance (the number of elements) and the "capacity" of the underlying HASHMAP instance (the number of buckets).  Therefore, if the iteration performance is important, do not set the initial capacity too high (or set the load factor too low). Attention This implementation is not synchronous. If multiple threads access a hash set at the same time, and at least one of the threads modifies the set, it must remain externally synchronized. This is usually done by performing a synchronous operation on the object that naturally encapsulates the set. If such an object does not exist, you should use the Collections.synchronizedset method to "wrap" the set. It is a good idea to do this at creation time to prevent accidental, out-of-sync access to the set:
Set s = collections.synchronizedset (new HashSet (...));
Note that the fast failure behavior of iterators is not guaranteed because, in general, it is not possible to make any hard guarantees as to whether or not there is a concurrency change in sync. The fast-failing iterator throws concurrentmodificationexception at its best. Therefore, it is a bad practice to write a program that relies on this exception to improve the correctness of such iterators: The fast failure behavior of iterators should only be used to detect bugs. Linkedhashset  A hash table and a link list implementation of a Set interface with predictable iteration order. This implementation differs from HashSet in that the latter maintains a double-link list that runs on all items. This list of links defines the order of iterations, that is, the order in which the elements are inserted into the set (insert order). Note that the insertion order is not affected by the elements that are reinserted in the set. (If S.add (e) is called immediately after S.contains (e) Returns True, the element e is reinserted into set S. This class provides all optional Set operations, and allows null elements. Like HashSet, it provides stable performance for basic operations (add, contains, and remove), assuming that the hash function correctly distributes elements into the bucket. Because of the increased expense of maintaining the list of links, the performance is likely to be more lesser than HashSet, but this is an exception: the time required for the linkedhashset iteration is proportional to the size of the set, regardless of capacity.   HashSet iterations are likely to cost more because the iteration time it takes is proportional to its capacity. The linked hash set has two parameters that affect its performance: the initial capacity and the load factor. They are very much the same as those defined in HashSet.   Note that a very high value selection for the initial capacity has a smaller effect on this class than the HashSet because the iteration time of this class is not affected by capacity. Attention This implementation is not synchronous. If multiple threads access a hash set at the same time, and at least one of the threads modifies the set, it must remain externally synchronized. This is usually done by performing a synchronous operation on the object that naturally encapsulates the set. If such an object does not exist, you should use the Collections.synchronizedset method to "wrap" the set. It is a good idea to do this at creation time to prevent accidental, out-of-sync access to the set:
Set s = collections.synchronizedset (new linkedhashset (...));
Note that the fast failure behavior of iterators cannot be guaranteed and, in general, there is no strong guarantee that there is a concurrency change that is not synchronized. The fast-failing iterator does its best to throw concurrentmodificationexception. Therefore, the way to write a program that relies on this exception is wrong, and the correct approach is that the fast failure behavior of the iterator should only be used to detect program errors. TreeSet  Navigableset implementation based on TREEMAP.   The elements are sorted using the natural order of the elements, or sorted according to the Comparator provided when the set was created, depending on the construction method used.   This implementation provides a guaranteed log (n) time overhead for basic operations (add, remove, and contains). Note that if the set interface is to be implemented correctly, the order of Set maintenance (whether or not an explicit comparer is provided) must be consistent with equals. (for a precise definition consistent with equals, see comparable or Comparator.) This is because the set interface is defined by the equals operation, but the TreeSet instance uses its compareTo (or Compare) method to compare all elements, so from the set point of view, this method considers that the two elements that are equal are equal.   Even if the set order is inconsistent with equals, its behavior is well-defined; it simply violates the general contract of the set interface. Attention This implementation is not synchronous. If multiple threads access a TreeSet at the same time, and at least one of the threads modifies the set, it must be externally synchronized. This is typically done by synchronizing the objects that naturally encapsulate the set. If such an object does not exist, you should use the Collections.synchronizedsortedset method to "wrap" the set. This is best done at creation time to prevent accidental non-synchronous access to set:
Set s = collections.synchronizedset (new TreeSet (...));
Note that the fast failure behavior of iterators is not guaranteed and, in general, there is no guarantee of any certainty when there are concurrent changes that are out of sync. The fast-failing iterator does its best to throw concurrentmodificationexception. Therefore, the practice of writing a program that relies on this exception is wrong, and the correct approach is that the fast failure behavior of the iterator should be used only to detect bugs. Copyonwritearrayset  Use internal copyonwritearraylist Set for all of its operations.   Therefore, it shares the following same basic properties: 1, it is best suited for applications that have the following characteristics: The set size is typically kept small, read-only operations are much larger than mutable operations, and there is a need to prevent conflicts between threads during traversal. 2, it is thread-safe。   3, because the entire underlying array is usually copied, variable operations (add, set, remove, and so on) are expensive.   4. The iterator does not support variable remove operations. 5. Traversing with iterators is fast and does not collide with other threads. When you construct an iterator, the iterator relies on the invariant array snapshot. Concurrentskiplistset  A concurrentskiplistmap-based scalable concurrency Navigableset implementation.   Set elements can be sorted according to their natural order, or they can be sorted according to the Comparator provided when the set is created, depending on the construction method used. This implementation provides the expected average log (n) time overhead for contains, add, remove operations, and their variants. Multiple threads are safe to ConcurrencyPerform insert, remove, and access operations. Iterators are weakly consistent, and the returned elements reflect the set state at the time the iterator was created or at some point after it was created. They do not throw concurrentmodificationexception and can handle other operations concurrently.   The ascending sort view and its iterators are faster than sorting the view and its iterators in descending order. Note that unlike in most collection, the size method here is not a fixed-time (constant-time) operation. Because of these set async attributes, determining the current number of elements requires traversing the elements. In addition, bulk operations AddAll, RemoveAll, Retainall, and Containsall are not guaranteed to be performed atomically (atomically).   For example, an iterator that works concurrently with a addall operation can only view certain additional elements. This class and its iterators implement all the optional methods of the Set and Iterator interfaces. Like most other concurrent collection implementations, this class does not allow null elements, because null parameters and return values cannot be reliably distinguished from non-existent elements. Queue  The collection used to hold the element before it is processed. In addition to the basic Collection operations, queues provide additional insert, fetch, and check operations. Each method has two forms: one throws an exception (when the operation fails), and the other Returns a special value (null or FALSE, depending on the action).   The latter form of the insert operation is designed specifically for the capacity-constrained Queue implementation, and in most implementations, the insert operation does not fail. Queues typically (but not necessarily) order individual elements in FIFO (first-in, in-order) manner. However, the priority queue and the LIFO queue (or stack) exception, which sorts elements according to the natural order of the provided comparer or element, which sorts the elements by LIFO (LIFO). Regardless of the sort method used, the header of the queue is the element that is removed by calling remove () or poll (). In the FIFO queue, all new elements are inserted at the end of the queue. Other kinds of queues may use different element placement rules.   Each QUEUE implementation must specify its order properties. Queue implementations generally do not allow the insertion of NULL elements, although some implementations, such as LinkedList, do not prohibit the insertion of NULL.   Even in implementations that allow Nulls, NULL should not be inserted into the queue because Null is also used as a special return value for the poll method, indicating that the queue does not contain elements. The queue implementation typically does not define an element-based version of the Equals and Hashcode methods, but inherits the identity-based version from the Object class, because element-based equality is not always well-defined for queues that have the same elements but have different sorting properties. Concurrentlinkedqueue  A node-based, link-free, thread-safe queue. This queue sorts the elements according to the FIFO (first-in, in-out) principle. The head of the queue is the longest element in the queue. The tail of the queue is the element with the shortest time in the queue. The new element is inserted at the end of the queue, and the queue get operation obtains the element from the queue head. Concurrentlinkedqueue is an appropriate choice when multiple threads share access to a common collection.   This queue does not allow the use of NULL elements. Memory consistency Effect: when there are other concurrent collection, the action in the thread before Concurrentlinkedqueue is placed in the Happen-before and then from the Concurrentlinkedqueue The operation that accesses or removes the element. List  An ordered collection (also known as a sequence). Users of this interface can precisely control the insertion position of each element in the list.  The user can access the element based on the integer index of the element (where it is located in the list) and search for the elements in the list. Unlike set, a list usually allows repeating elements. More specifically, lists generally allow for e1.equals (E2) elements to E1 and E2, and if the list itself allows null elements, they usually allow multiple null elements.  It's hard to avoid repeating lists by throwing a run-time exception when a user tries to insert a repeating element, but we hope that the less you can use it, the better. Note: Although the list allows itself to be included as an element, it is recommended to be particularly cautious: on such lists, the Equals and Hashcode methods are no longer well-defined. ArrayList  The implementation of a variable array of size for the List interface. All optional list operations are implemented and all elements, including NULL, are allowed. In addition to implementing the list interface, this class provides methods to manipulate the size of the array used internally to store the list. (This class is roughly 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 fixed time of allocation, that is, an O (n) time is required to add n elements. All other operations run in linear time (broadly speaking).  This implementation has a low constant factor compared to the constant factor used for LinkedList implementations. Each ArrayList instance has a capacity. This capacity refers to the size of the array used to store the list elements. It is always at least equal to the size of the list. As you add elements to the ArrayList, their capacity increases automatically.  The details of the growth strategy are not specified, as it is not just the addition of elements that can be as simple as allocating fixed-time overhead. Before adding a large number of elements, an application can use the ensurecapacity operation to increase the capacity of the ArrayList instance.  This can reduce the amount of incremental redistribution. Attention This implementation is not synchronousLinkedList  The list interface is implemented as a link listing. Implements all optional list operations, and allows all elements (including null). In addition to implementing the list interface, the LinkedList class provides a uniform naming method for the 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 double-ended queue.  This class implements the Deque interface for Add, poll, and other stack and double-ended queue operations. All actions are performed as required by the list of double links.  Indexing in the list iterates through the list from the beginning or end (from one end near the specified index). Attention This implementation is not synchronouscopyonwritearraylist  A thread-safe variant of ArrayList, where all mutable operations (add, set, and so on) are implemented by a new copy of the underlying array. This typically requires a lot of overhead, but this approach may be more efficient than other workarounds when the number of traversal operations greatly exceeds the number of variable operations. It is also useful when you cannot or do not want to perform synchronous traversal, but you need to exclude conflicts from concurrent threads. The snapshot style iterator method uses a reference to the array state when creating the iterator. This array does not change during the lifetime of the iterator, so there is no possibility of collisions and the iterator guarantees that concurrentmodificationexception will not be thrown. When an iterator is created, the iterator does not reflect the addition, removal, or change of the list. Element change operations (remove, set, and add) that are made on iterators are not supported.   These methods will throw unsupportedoperationexception.   Allows all elements to be used, including null. Memory consistency Effect: when there are other concurrent collection, the action in the thread before copyonwritearraylist is placed in the Happen-before and then from the Copyonwritearraylist The operation to access or remove the element in the Vector  Vector classes can implement an array of objects that can grow. Like an array, it contains components that can be accessed using an integer index.   However, the size of the vector can be increased or reduced as needed to accommodate the addition or removal of items after the vector is created. Each vector attempts to optimize storage management by maintaining capacity and capacityincrement. The capacity should always be at least equal to the size of the vector; This value is usually larger than the latter because the storage will increase by the size of the capacityincrement as the component is added to the vector. The application can increase the capacity of the vector before inserting a large number of components, thus reducing the amount of increased redistribution. Stack  The Stack class represents a last-in, first-out (LIFO) object heap. It extends the class vector by five operations, allowing the vector to be treated as a stack.   It provides the usual push and pop operations, and the Peek method that takes the stack vertex, the empty method that tests if the stack is null, the search method that finds the item in the stack, and determines the distance to the top of the stack.   When the stack is first created, it does not contain items. The Deque interface and its implementation provide a more complete and consistent set of LIFO stack operations, which should be used preferentially rather than this class. For example:
New Arraydeque<integer> ();

Collection of the Java collection framework

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.