A comprehensive summary of Java container-related knowledge

Source: Internet
Author: User

The Java Utility Class Library provides a fairly complete set of containers to help us solve many specific problems. Because I am an android developer, including me a lot of Android development, the best thing is the ListView (recycleview) +baseadapter+arraylist three musketeers, The containers used in contact with the usual only ArrayList and hashmap. This leads to a very shallow level of mastery and use of the entire Java container System. The province is not enough to think about improvement, then follow me to summarize the Java container knowledge.

Structure
    • Inheritance structure of Java container classes
    • Specific introduction
      • Iterators
      • Collection
        • List
        • Set
        • Queue
      • Map
    • Some suggestions
    • Advanced • Concurrent Containers
      • Copyonwritearraylist and Copy-on-write Strategy
      • Concurrentlinkedqueue
      • Concurrenthashmap and Lock Segmentation Technology
      • blocking queues
Inheritance structure of Java container classes

The Java Container Class library defines two different concepts of containers, collection and map

    • Collection A sequence of independent elements that obey one or more rules. The list must save the elements in the order in which they are inserted. Set cannot have duplicate Elements. The queue determines the order in which the objects are produced, according to the queuing rules.

(the JDK Source code version of the article has no special instructions are JDK1.8.0_101)

  public InterfaceCollection<e>extendsIterable<e> {        intsize (); BooleanIsEmpty (); Booleancontains (Object o); Iterator<E>iterator ();        object[] ToArray (); <T>t[] ToArray (t[] a); BooleanAdd (e e); BooleanRemove (Object o); BooleanContainsall (java.util.collection<?>c); BooleanAddAll (java.util.collection<?extendsE>c); BooleanRemoveAll (java.util.collection<?>c); ... //other methods are omitted}

As you can see, Java defines the basic operating methods of the collection interface and the internal collection, and collection by default can add elements to the end of the collection, delete the specified elements, and so On. The List, Set, and queue interfaces inherit from the collection and define their own different methods.

    • Map A pair of "key-value pairs" objects that allow us to use keys to look up Values.

 public InterfaceMap<k,v> {        intsize (); BooleanContainsKey (Object key); BooleanContainsvalue (Object value);        V Get (Object key);        V put (K key, v value);        V Remove (Object key); voidPutall (java.util.map<?extendsK?extendsV>m); voidClear (); Set<K>KeySet (); Collection<V>Values (); Set<java.util.map.entry<k, v>>EntrySet (); InterfaceEntry<k,v>{K GetKey ();            V GetValue ();            V SetValue (v value); Booleanequals (Object o); inthashcode ();        ...        } Booleanequals (Object o); inthashcode (); }

The map internal interface entry<k,v> corresponds to the key value pairs of the map.

Specific introduction to Iterators

Let's introduce an Iterator. The iterator itself is also a design pattern, the original idea is: the implementation of the container by many kinds, and we want to traverse the container, first of all should not care about the details of the container implementation, and then the traversal operation should be lightweight. Iterators unify the way the container is accessed, and the cost of creating it is minimal. It is important to note that iterator can only be moved one way.

 public InterfaceIterator<e> {        BooleanHasnext ();        E Next (); default voidRemove () {Throw NewUnsupportedoperationexception ("remove"); }        default voidForeachremaining (consumer<?SuperE>Action)            {objects.requirenonnull (action);  while(hasnext ()) action.accept (next ()); }    }

The Container's iterator is obtained through the Container's iterator () method
Next () of the iterator gets the next element
Hasnext () Determine if there are elements
Remove () deletes the specified element

Listiterator

Listiterator is an extension of iterator for various list class accesses and supports bidirectional Movement.

Collectionlist

The List promises to maintain elements in a particular sequence. The list interface adds a number of methods based on the collection, allowing you to insert and remove elements in the middle of a list.

 public InterfaceList<e>extendsCollection<e> {        ...        BooleanAdd (e e); BooleanRemove (Object o); BooleanContainsall (collection<?>c); BooleanAddAll (collection<?extendsE>c); BooleanAddAll (intindex, collection<?extendsE>c); BooleanRemoveAll (collection<?>c); BooleanRetainall (collection<?>c); E Get (intindex); E Set (intindex, E element); voidAddintindex, E element); E Remove (intindex); intindexOf (Object o); intlastIndexOf (Object o); Java.util.List<E> sublist (intfromIndex,inttoindex); ...    }

There are two types of list,arraylist and LinkedList

the
List Type Advantages Disadvantagesunderlying implementation
ArrayList Faster random access elements Slow insertion and deletion of intermediate elements Array
LinkedList Insertion and deletion of intermediate elements, optimization of sequential access Slow random access elements Doubly linked list
Set

Set does not save duplicate elements, which are often used to quickly find Elements. It is worth mentioning that the set has exactly the same interface as the collection, without any additional Functionality. The deposited element must define the equals () method

the
set Type Usage Scenariosunderlying implementation
HashSet Quick find, element must define Hashcode () Linked list
TreeSet Keep order, element must implement comparable interface Red-black tree structure
Linkedhashset HashSet of maintenance order, elements must be defined hashcode () Linked list

Queue

In addition to concurrent applications, the only two implementations of the queue are LinkedList and priorityqueue, where LinkedList simultaneously implements the list, deque interface. They differ in the sort behavior rather than the Performance.

 public Interface extends collection<e> {        boolean  add (e e);         Boolean offer (e e);        E Remove ();        E Poll ();        E element ();        E Peek ();    }

Map the
Map Type Usage Scenariosunderlying implementation
HashMap Quick Query Hash table
Linkedhashmap Iterative traversal with order (insert order or least recently Used) Linked list
TreeMap Map with sort, only can return subtree (subMap ()) Red-black tree structure
Weakhashmap Weak key mappings, non-referenced keys outside the map, can be garbage collected Hash table
Concurrenthashmap Thread-safe Map Linked list
Identityhashmap Use = = instead of equals () to sort the keys to solve special problems Linked list

We can manually adjust the HashMap to adjust performance, involving concepts such as capacity, initial capacity, size, load factor, and so On. If you are interested, you can read some relevant Information.

Some suggestions
    • Do not use outdated containers such as the vector enumeration Hashtable stack (yes, This is Java's original bad design, the actual use of the stack is recommended Linkedlist)
Advanced • Concurrent Containers

This is not a very detailed implementation, just a brief introduction to the basics, interesting to read the book "the Art of Java concurrent programming".

Copyonwritearraylist and Copy-on-write Strategy

Copy-on-write abbreviation cow, is a kind of optimization strategy used in program DESIGN. The basic idea is that from the beginning everyone is sharing the same content, when someone wants to modify the content, it will really copy the content to form a new content and then change, this is a delay lazy strategy. Starting with JDK1.5 Java Concurrency Package provides two concurrent containers implemented using the Copyonwrite mechanism, which are copyonwritearraylist and copyonwritearrayset. The Copyonwrite container is very useful and can be used in very many concurrent scenarios.

The Copyonwrite container is the container that is copied when it is Written. The popular understanding is that when we add elements to a container, instead of adding them directly to the current container, the current container is copied, a new container is duplicated, the new container is added, the element is added, and the reference to the original container is pointed to the new container. The advantage of this is that we can read the Copyonwrite container concurrently, without having to lock it, because the current container does not add any Elements. So the Copyonwrite container is also a reading and writing separation of ideas, reading and writing different Containers.

The Copyonwrite container can only guarantee the final consistency of the data and cannot guarantee the real-time data consistency. So if you want to write the data that can be read right away, please do not use the Copyonwrite container.

Concurrentlinkedqueue

In concurrent programming, it is sometimes necessary to use a thread-safe queue or List. There are usually two ways to implement thread safety, one is to use a blocking algorithm, and one is to use a non-blocking algorithm. The non-blocking algorithm is implemented based on a cyclic CAS (Compare and Swipe comparison and exchange).

The implementation of Concurrentlinkedqueue technology is similar to copyonwritearraylist with copy, but only some parts of the container, not the entire container, can be copied and Modified. Concurrentlinkedqueue consists of a head node and a tail node, each node consisting of a node element (item) and a reference to the next node (next). Nodes are linked by next to form a queue of linked list Structures.

Concurrenthashmap and Lock Segmentation Technology

Concurrenthashmap is a thread-safe and efficient hashmap. In a multithreaded environment, using Non-thread-safe HashMap can lead to a dead loop, and, as suggested in the article, hashtable this obsolete container is inefficient (using synchronized to ensure thread safety). Concurrenthashmap uses lock segmentation technology, which greatly improves the efficiency of concurrent use.

Lock segmentation Technology: Assuming that the container has multiple locks, each lock is used to lock the container part of the data, when the multi-threaded access to different data segments of the container data, there is no lock competition between the threads, thereby improving the efficiency of concurrent ACCESS.

blocking queues

JDK7 provides 7 blocking queues, and the implementation principle is based on the production-consumption mode of the wait notification Mechanism.

Blocking Queue Types features
Arrayblockingqueue Bounded blocking queues consisting of array structures
Linkedblockingqueue Bounded blocking queues consisting of linked list structures
Priorityblockingqueue Unbounded blocking queues that support priority ordering
Delayqueue Unbounded blocking queues implemented with priority queues
Synchronousqueue Blocking queues that do not store elements
LinkedTransferQueue Unbounded blocking queues made up of linked list structures
Linkedblockingqueue A two-way blocking queue consisting of linked list structures

Thanks for reading ~

A comprehensive summary of Java container-related knowledge

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.