Overview of Collection framework and collection framework

Source: Internet
Author: User
Tags concurrentmodificationexception

Overview of Collection framework and collection framework


A collection is a group of composite elements used to store, retrieve, control aggregated data, and provide communication methods between them.

Java's collection framework provides a unified architecture for expressing and manipulating collections. All collection frameworks have the following three aspects:

Interface: The abstract data structure of the set. The interface allows us to manipulate the set independently without considering the specific implementation of the Set.

Implementation: The specific implementation class of the interface. Essentially, they are reusable data structures.

Algorithm: Perform useful calculations, such as sorting and searching, on the objects that implement the set interface. The algorithm isPolymorphism: Methods with the same name can be called by any appropriate interface implementation class. In essence, algorithms are reusable functions.

 

The core set interfaces encapsulate different types of sets, which are the basis of the java set framework and form the hierarchical structure shown in


We can see that Set is a special Collection, and SortedSet is a special Set ...... And so on.

Note that there are two different trees. Map is not a Collection sub-interface, but an independent interface.

All set interfaces are generalized. For example, the following is a Collection interface declaration:

Public interfaceCollection <E>...

"<E>" indicates that this interface is common. When declaring a Collection interface, it is best to specify the object type contained in this interface, so that the compiler can check whether the input object is correct during compilation, thus reducing the errors thrown during runtime.

Many methods in the interface can be implemented. That is to say, its implementation class can implement or not implement this method. It is determined based on specific needs.

 

First, let's take a look at the core set interfaces and have an overall perceptual knowledge of them:

Collection Interface: The Root Interface of the Collection framework. It is the most general top-level interface in the Collection class framework. The Java platform does not provide any specific implementation classes for this interface, but provides subinterfaces with different features.

Set Interface: A set that contains duplicate values is not allowed.

List Interface: An indexed set that can contain duplicate values. When using this interface, we use indexes to precisely insert and search elements.

Queue Interface: This set is suitable for organizing a queue. The elements in the queue are processed by priority. In addition to the methods inherited from the Collection interface, this interface also provides additional insertion, extraction, and validation methods. A typical queue complies with the "FIFO: First In, First Out" principle. A priority queue is an exception that sorts elements In order of priority. No matter what the order is, the Header element is always checked out first. The sorting principle must be specified for the Implementation class of each Queue interface.

Deque Interface: Unlike Queue, It is a dual-end Queue that inserts and removes elements at both ends. It inherits and extends the Queue interface.

Map Interface: Provides a set of key/value mappings. Duplicate values are not allowed for keywords. One value can be mapped to multiple keywords.

SortedSet Interface: Maintains the order of elements in the Set in ascending order.

SortedMap Interface: Maintain the order of elements in the set based on the principle of keyword ascending

 

The general implementation classes of the above interfaces (the general implementation classes here generally refer to the implementation classes applicable to single-threaded environments, and the JDK has special implementation classes for multi-threaded Concurrent Environments) are summarized as follows:

Interface

Hash Table Implementation

Variable Array Implementation

Tree implementation

Linked List Implementation

Hash Table + Linked List Implementation

Heap implementation

Set

HashSet

 

TreeSet

 

LinkedHashSet

 

List

 

ArrayList

 

Shortlist

 

 

Queue

 

 

 

Shortlist

 

PriorityQueue

Deque

 

 

 

Shortlist

 

 

Map

HashMap

 

TreeMap

 

LinkedHashMap

 

It can be found that the Queue List implements the List, Queue, and Deque interfaces at the same time.

The SortedSet interface and SortedMap interface are not listed in the preceding table. In the above hierarchy structure, we can see that they are the sub-interfaces of Set and Map, and TreeSet and TreeMap are their implementation classes.

All the general implementation classes mentioned above support null elements (or key/value), but some can only contain one null, and some can contain multiple null; all general implementation classes implement Serializable, which is a Serializable object. All general implementation classes provide a clone method for copying objects. All general implementation classes areThread Security(That is, not synchronized); all general implementation classes provide"Fail-fast"Mechanism iterator

For the "fail-fast" mechanism, let's look at an example:

     Map<String,String> map = new HashMap<String,String>();             map.put("first", "Jay");             map.put("second","Jack");             map.put("third", "Jim");                         Iterator<String> it= map.keySet().iterator();             while(it.hasNext()){                    System.out.println(map.get(it.next()));                    if(map.containsKey("second")){                           map.remove("second");                    }             }
 

The above code tries to use Iterator to iterate the key value in Map. If the key value is "second", the element in Map is deleted. After running the command, you can find that java. util. ConcurrentModificationException is reported when you perform the delete operation, even if this is a single thread.

Iterator works in an independent thread and has a mutex lock. After the Iterator is created, a single-chain index table pointing to the original object will be created. When the number of original objects changes, the content of the index table will not change simultaneously, therefore, when the index pointer moves backwards, the object to be iterated cannot be found. Therefore, Iterator will immediately throw java according to the fail-fast principle. util. concurrentModificationException exception.

However, if the above Code does not perform the delete operation, but overwrites the original elements:

if(map.containsKey("second")){      map.put ("second","Joe");}

No error will be reported. The Iterator in the above program iterates the Map Key. Although the Map is modified, only the value of one element is changed, and the KeySet of the entire Map is not changed.

If you want to successfully perform the delete operation, you must first Delete the Iterator.

Map <String, String> map = new HashMap <String, String> (); map. put ("first", "Jay"); map. put ("second", "Jack"); map. put ("third", "Jim"); Iterator <String> it = map. keySet (). iterator (); while (it. hasNext () {System. out. println (map. get (it. next (); if (map. containsKey ("second") {it. remove (); // Delete the map of the Iterator first. remove ("second ");}}

In addition to the implementation classes mentioned above, there are two types of implementation classes that are not commonly used: VectorAnd Hashtable, They are thread-safe.This is a legacy product of a lower version of JDK. For collections, thread security is not required in most cases. In a multi-threaded environment, JDK also provides multiple methods to convert the above general implementation class into a thread-safe class.

If multiple threads access an implementation class at the same time, and at least one thread modifies the class, 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, useCollections. synchronizedMapMethod To "Wrap" map. It is best to complete this operation at creation to prevent unexpected non-synchronous access to the set:

Map map = Collections.synchronizedMap(newHashSMap(...));



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.