Java Collections Framework

Source: Internet
Author: User

Java Collections Framework
Set OR containerWe usually use arrays to save some basic data types. arrays are supported by the compiler, but an obvious disadvantage of arrays is that they have fixed sizes. In general, only when the program is running can we know the specific number of files to be saved. Java class library provides a complete set of container frameworks to solve this problem. The basic types are List, Set, Queue, and Map. These object types are also called Collection classes. However, because the Collection name is used in Java to refer to a subset of the class library, the more widely used term is "container. The basic task of the container is to save the object. More accurately, it is to save the object reference. However, the implementations of various containers are quite different. None of them are absolutely good enough to adapt to all application scenarios. Therefore, we need to understand the underlying implementations of various containers, then select the appropriate container based on the actual situation. From the following container classification diagram, we can see the huge Collections Framework, and this does not include the implementation of the Queue interface (PriorityQueue and BlockingQueue of various styles) concurrentMap interface implementation, CopyOnWriteArrayList and CopyOnWriteArraySet, EnumSet and EnumMap, and multiple tool methods in the Collections tool class.


Interface specifications: Collections Framework defines some interface specifications. Common Containers inherit some interface specifications, and each interface provides the corresponding abstract class, if the containers provided by the class library cannot complete the tasks you specify, you can expand the subclasses of these abstract classes and customize your own containers.
Collection Interface: It only represents a set of objects without specifying the storage order of objects and whether repeated elements can be contained. The Collection interface also inherits the Iterator interface. Many containers have implemented Collection interfaces, including List, Set, Queue, and Deque. Note that the Map of the same container does not implement the Collection interface. The Collection interface defines the most basic features of the container, including the following interface method definition: size method: return the number of elements in the container isEmpty method: return whether the container is empty contains method: return whether the container contains an element iterator method: Return to the container iterator add method: Used to add elements to the container remove Method: Used to delete elements in the container clear method: to clear the element toArray in a container, convert the container class to an array of objects.

List Interface: List is inherited from the Collection interface, indicating an ordered container. Elements in the container are stored in an ordered order according to the added order. Repeated elements are allowed and can be accessed Based on element locations. The List interface adds the following method definition to the Collection interface: get method: gets the element set at the specified position: sets the specified position to the specified Element indexOf: obtain the location of the specified Element in the container listIterator: returns the ListIterator type iterator subList: obtains the sub-container of the container according to the range position.
Common Implementation classes of the List interface include ArrayList, sorted List, and Vector.


Set Interface: Inherits from the Collection interface. It features that it cannot store the same elements and has no requirements for ordering. The method definition in the Set interface is basically the same as that in the Collection interface, and no new method definition is added.
Common Set interfaces include HashSet and SortedSet interfaces.

Queue Interface: Inherited from the Collection interface, it is a container defined to store a series of elements waiting for a specific process. Besides some basic container operations, the Queue also provides some additional insert, extract, and check operations.
The Queue interface defines the following method: add method: insert the specified element into this Queue (if it is feasible immediately and does not violate the capacity limit), return true upon success, if no space is available, IllegalStateException is thrown. Offer method: inserts a specified element into this queue (if immediately feasible and does not violate the Capacity Limit). When using a queue with a capacity limit, this method is generally better than add (E ), the latter may not be able to insert elements, but only throws an exception. Peek method: Get but do not remove the header of this queue; if this queue is empty, return null. Pool method: gets and removes the header of this queue. If this queue is empty, null is returned. Remove Method: Get and remove the queue header. The Deque and BlockingQueue interfaces are both directly inherited from the Queue interfaces.

Map Interface: Is a ing set of key and value. Each key corresponds to a value.
Some basic methods defined in the Map interface: size method: return the number of elements in the container put method: add elements to the container remove Method: Delete the elements in the container isEmpty method: method for determining whether the container is empty contains: method for determining whether the container contains the specified element clear: Method for clearing the element keySet in the container: return the key set of Map, is a Set type that implements some Map interface classes: HashMap, Hashtable, WeakHashMap, SynchronizedMap, ConcurrentMap interface, etc.

Deque Interface: Inherited from the Queue interface. It is added to JDK1.6, also known as a dual-end Queue. It can be inserted and extracted at both ends of the Queue. Based on the Queue interface, the Deque interface adds addFirst, addLast, offerFirst, and offerLast methods to indicate that these operations can be performed on both ends.
Common Deque implementation classes include ArrayDeque, concurrentincludeque, shortlist, and BlockingDeque.

Collections Framework also contains some other interfaces, but these interfaces are basically extended, such as SortedSet, SortedMap, BlockingQueue, BlockingDeque, and ConcurrentMap.
______________________________________________________________________________________________________________________________________________________________________
Common Implementation classesThe Class Library provides some very useful container implementation classes based on the above interfaces, and is well qualified for most of the scenarios in daily development.
HashSet: The implementation of Hash tables based on the Set interface fully implements the Set interface. The order of elements in the container is unordered, and the underlying implementation is based on HashMap. The key indicates the China value of the set container, and the value is the same object, the put Method of HashMap.
TreeSet: Implemented based on the red/black tree and inherited from the NavigableSet interface. NavigableSet, that is, SortedSet extension, provides a navigation method that is closest to matching items for a given search Target report.
LinkedHashSet: Inherits from the HashSet class, implements the Set interface, and has a predictable iteration orderSetInterface hash table and link list implementation. This implementation worksHashSetIn addition, 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.
ArrayList: The List interface is implemented. The underlying layer is implemented based on arrays. Random Access to elements is faster, but insertion and deletion operations are slower.
Shortlist: The List interface and Deque interface are implemented. The underlying layer is the dual linked List implementation. The insert and delete operations on elements are fast, but the random access performance is poor. When using a queue, the queue list is a FIFO queue.
ArrayDeque: Deque is an efficient array-based implementation of the Deque interface.
PriorityQueue: It is an unbounded priority queue based on the priority heap.
HashMap: The implementation of the Map interface based on the hash table allows the use of NULL values and keys, except for non-synchronous and can use null, and HashTable is roughly the same,
TreeMap: It is implemented based on the NavigableMap of the red and black trees. The ing is sorted based on the natural sequence of the keys or the Comparator provided during creation.
LinkedHashMap: Implement the hash table and linked list of the Map interface, with an expected iteration order.
_________________________________________________________________________________________________________________________________
Packaging implementation classA series of static internal class containers are provided in the java. util. Collections tool class. These internal classes also implement the Collection interface and have their own features, which can be divided into the following three categories: Collections. unmodifiableInterface: Containers of the specified Interface type are returned, but users are not allowed to modify them. It is equivalent to an unchangeable view of the original container. Collections. synchronizedInterface: Return the container of the specified interface type, but it is thread-safe. Collections. checkedInterface: Return a dynamic security view of the specified interface. Inserting an element of the Error Type will immediately throw ClassCastException. ___________________________________________________________________________________________________________________________________
Feature-based implementation:
WeakHashMap: Containers are used to save objects. More accurately, they are used to save object references. If a container with a long life cycle keeps a reference of useless objects, GC cannot be recycled. WeakHashMap usesWeak keyImplemented hash table-basedMap. InWeakHashMapWhen a key is no longer in use, its entries are automatically removed. More precisely, for a given key, the existence of its ing does not prevent the garbage collector from discarding the key, which makes the key terminable and terminated, then it is recycled. When a key is discarded, its entries are effectively removed from the ing.MapThe implementation varies.IdentityHashMap: This class is implemented using a hash tableMapInterface. When comparing keys (and values), use the reference equality to replace the object equality. In other wordsIdentityHashMapWhen and only when(K1 = k2)Only two keys are consideredK1AndK2Equal.CopyOnWriteArrayList: A thread-safe variant of ArrayList, where all variable operations (Add,SetAnd so on) are implemented by performing a new copy on the underlying array, which usually requires a large overhead.CopyOnWriteArraySeT: The CopyOnWriteArrayList Set is used internally.EnumSet: Dedicated Set implementation used with enumeration types. All keys in the enumeration set must come from a single Enumeration type, which is explicitly or implicitly specified when the set is created.
EnumMap: Special Map implementation used with enumeration types. All keys in the enumeration ing must come from a single Enumeration type, which is explicitly or implicitly specified when the ing is created. The enumeration ing is represented as an array internally. This representation is very compact and efficient.
----------------------------------------------------------------------Implementation class for concurrent use:
Concurrent1_queue: A connection node-based unbounded thread-safe queue that sorts elements according to the FIFO principle.ConcurrentHashMap: The hash table that supports obtaining full concurrency and updating the expected adjustable concurrency is implemented based on non-blocking.LinkedBlockingQueue: A blocking queue Based on a linked node with any range. It is also a FIFO sorting element.PriorityBlockingQueue: The implementation of a blocking queue with a priority.
Other concurrent containers can be found in the java. util. concurrent package.



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.