Hidden design routines In the Java collection framework

Source: Internet
Author: User

Our world should not only have "carrots"

Let me pull something else out before I get to the point.

A recent sudden thought of a donkey and a carrot had to tell the story. Said is a person sitting on the back of a donkey, with a long rod tied with a carrot, and then put the carrot hanging in front of the donkey, the donkey thought that as long as a step forward can eat carrots, so keep going forward, but it always can not eat this radish.

1000 readers will have 1000 hamlet, of course, different people will have different understanding of the story. For example, we work desperately for life, but never reach financial freedom, we are also like a busy "donkey" it?

Therefore, our world should not only "carrots".

Do not know the truth, only the body in this mountain. Sometimes jumping out, using "God's Perspective" to look at this world of our existence, perhaps there will be a different discovery. Life is so, so is learning.

Data structures and algorithms with the Java Collection framework

Let's look at a story next. The story is purely fictitious, if there is a similar, you copy me.

Date: 2017/01/11

Location: Company A Office

People: Xiao Ming-a job for a year Android small rookie; b Big--a, Android development leader, Android senior development engineer

Cause: Xiao Ming thought of a company to work, by B greatly interviewed him.

After: B Greatly said, Xiao Ming Ah, you just graduated a year, the algorithm should be good, let's start with a simple bar. There is a maze of n rows of M-column cells, each of which is either an open space or an obstacle, and obstacles cannot be traversed. Any of the two not obstacles and different points P and Q, how to find the shortest path p to Q?

Xiao Ming, the side of his heads and said, that B big, I go to school when the fun did not learn data structure and algorithms, after graduation work also basically no use, all not very will ...

b greatly revealing a comforting expression, saying, well, understandable. Let's ask some of the usual work.

Xiao Ming suddenly came to the spirit, a chicken peck-like nod.

b Big say, then you talk about your work in contact with the data structure it.

Xiao Ming's mouth is coming, array, ArrayList, Map.

b Big and wait for a while, see Xiaoming really did not have the following, and continue to ask, then you understand the Java Collection framework design ideas ?

Xiao Ming said, design ideas? Why to understand, no time ah, I write code is a shuttle! Copy, paste, pick up the keyboard is dry! Efficiency is just.

b Big heart 10,000 alpaca flew over, the corners of the mouth shook, said, that Xiao Ming, we today's interview on the first, there is the result I let HR inform you.

Then, then there was no then.

Although the story is fictitious, but it is not difficult to find out the reality version of Xiao Ming's job. So what can we reflect from this story?

First of all, the data structure and algorithms, design patterns of these belong to the internal strength, as the saying goes Lianquan not practicing, to the old one empty, with these internal strength we can better use all kinds of moves, otherwise just acts have their shape. To know that a showy is not much fighting power.

Secondly, understand the source of the design ideas, use to be more handy, but also to improve their design capabilities . And like the beginning, we should be good at looking at things from a macro perspective , so that we can see more and reap more. Of course, grow up as a senior engineer, marry mating, to the pinnacle of life is not a dream.

Data structures and algorithms

I'm not going to repeat the definition of the data structure and algorithm, the space-time complexity of the algorithm, but the characteristics of each data structure. Because the algorithm is similar to the general operation of the data structure, it basically includes insert, find, delete, traverse and sort , so we focus on the performance of these operations.

    • Array: The advantage is that the insert block, if you know the subscript, can be very fast access. The disadvantage is to find slow, delete slow, fixed size.
    • Ordered arrays: The advantage is faster than unordered array lookups. The disadvantage is that insertions and deletions are slow and fixed in size.
    • Stack: Provides access to the last-in, first-out mode. The disadvantage is that access to other items is slow.
    • Queues: provides FIFO access. The disadvantage is that access to other items is slow.
    • Linked list: The advantage is that insert fast, delete fast. The disadvantage is that lookups are slow.
    • Binary tree: The advantage is to find, insert, delete are fast (such as fruit trees to maintain balance). The disadvantage is that the deletion algorithm is complex.
    • Red-Haishi: The advantage is that the search, insert, delete are fast, the tree is always balanced. The disadvantage is that the algorithm is complex.
    • 2-3-4 Tree: The advantage is that the search, insert, delete are fast, the tree is always balanced, and similar trees are useful for disk storage. The disadvantage is that the algorithm is complex.
    • Hash table: The advantage is that if the keyword is known, the access is very fast and the insertion is fast. The disadvantage is that the deletion is slow, and if you do not know the keyword, the access is slow and the storage space is not used adequately.
    • Heap: The advantage is that the INSERT, delete fast, access to the largest data items quickly. The disadvantage is that access to other data items is slow.
    • Figure: Modeling the real world. Some algorithms are slow and complex.
The overall design of the collection framework in Java

Good design is always similar. It uses a good interface to encapsulate a specific function, which effectively uses CPU and memory, and so on.

The data structures we use are linear, stack, queue and so on, as well as collections and hash tables , so we only discuss the design of these structures.

Before we analyze the design of the Java Collection Framework, let's take a serious look at a question, what would you do if you were to design a collection framework for Java?

Xiao Ming's Practice

If it was a Ming Li design, I guess he would choose a simple and rude way to write a few classes to implement linear tables, stacks, queues, collections, and a hash table. Okay, so here's the question.

    1. If the user wants to customize a linear table that is implemented in its own way, what should he do?
    2. If the user starts using an unordered linear table and then because a requirement is changed to an orderly one, does the user need to make a big change?
    3. If Xiaoming is going to upgrade an existing API and add another higher performance implementation of the unordered linear table, how much does he need to change?

In fact, a summary of the three questions is nothing more than maintenance and expansion of the cost of the problem.

Our way of thinking

First of all, let's look at other features of the design ideas, such as the Android view class and the context class family . Let's analyze the hierarchy of their code.

The class diagram for the view class family is as follows

The class diagram for the context class family is as follows

Let's take a look at the similarities in the design of these two modules.

    • The whole code structure is like a tree with a unique root node that encapsulates the public properties of this class family
    • There is an abstract class or class that acts like an abstract class, and they implement a common approach. User-friendly expansion of their business.
    • There are specific implementations where the user can directly use these specific implementations.

These similarities can actually be summed up in three structural levels

    1. A highly abstract root node interface that abstracts a set of interfaces with specific operations to implement our root node
    2. A set of abstract classes that implement some of the methods with specific operating interfaces, allowing users to quickly expand their business.
    3. Specific implementation, convenient for users to call directly.

This routine is very common in Android source code, and the benefits are obvious and easier to maintain and extend .

The realization idea of source code

Then let's see if it's the same with the Java Collection Framework, as we said.

Let's take a look at the class diagram of the collection frame

This picture I found on the internet, but does not affect our analysis. If there is infringement, please tell me that I will delete it.

From this picture we can clearly see that the pattern is exactly the same.

First, because the similarities between map and collection are few, the root nodes of the two parts are separated.

Let's take collection. This section begins by defining a set of interfaces. Collection is a list, set and other sets of highly abstracted interface, it contains the basic operation of these sets , it is mainly divided into:list, set andqueue, respectively, corresponding to the linear table, set, queue, Implementation of the corresponding interface, there is a corresponding data structure of the characteristics. This is the first level of structure.

Then we define a set of abstract classes, we take the Abstractcollection class, first look at the comments

/** * This class provides a skeletal implementation of the <tt>Collection</tt> * interface, to minimize the effort required to implement this interface. <p> */

This class implements the skeleton of the collection interface, and the user inherits the class to implement a set with minimal time.

Other abstract classes are skeletons of individual data structures, and users can customize their own collections.

Finally, the third level is concrete implementation class, such as our common ArrayList, LinkedList and so on. For example, LinkedList implements the list and queue interfaces, so it has both the FIFO and the queue features, and the list can access the attributes of the elements through the location.

The specific implementation of the source code collection part

Collection is a set of list, set and other highly abstracted interface, it contains the basic operation of these sets , it is mainly divided into two parts:list and set.

Collection interface
/** * The rootInterface inchThe <i>collection hierarchy</i>. A collection * Represents aGroup  ofobjects, known asits <i>elements</i>. Some * Collections Allow duplicate elements andOthers Do  not. Some is ordered * andOthers unordered. The JDK does notProvide any <i>direct</i> * implementations ofThisInterface: It provides implementations ofMore * Specific subinterfaces like<tt>Set</tt> and<tt>list</tt>. ThisInterface* isTypically used toPass collections Around andManipulate themwhere* Maximum generality isDesired. */

The root of the collection hierarchy. A collection contains a set of element objects . There are some collections that allow repeating elements, some that are not allowed, and some that are ordered by some collection elements.

Define the method:

    • int size ()
    • Boolean IsEmpty ()
    • Boolean contains (Object o)
    • Iterator Iterator ()
    • Object[] ToArray ()
    • T[] ToArray (t[] a)
    • Boolean Add (E E)
    • Boolean remove (Object o)
    • Boolean containsall (Collection c)
    • Boolean AddAll (Collection c)
    • Boolean RemoveAll (Collection c)
    • Boolean retainall (Collection c)
    • void Clear ()
Iterator interface

An iterator interface for iterating through the collection.

    • Boolean Hasnext ()
    • E Next ()
    • default void Remove ()
    • default void foreachremaining (Consumer action)
Abstractcollection Abstract class
/** * ThisclassProvides a skeletal implementation of  the<tt>Collection</tt> * Interface, toMinimize theEffort required toImplement this interface. <p> * To implement an unmodifiable collection, theProgrammer needs only to* Extend thisclass  andProvide implementations for  the<tt>iterator</tt> and* <tt>size</tt> methods. (The iterator returned by  the<tt>iterator</tt> * Method must implement <tt>hasNext</tt> and<tt>next</tt>.) <p> * To implement a modifiable collection, theProgrammer must additionally * override thisclass' s <tt>add</tt> method (which otherwise throws an * <tt>UnsupportedOperationException</tt>), and  theIterator returned by  the* <tt>iterator</tt> method must additionally implement its<tt>remove</tt> * method.<p> * * The programmer should generally provide a void (no argument) and* <tt>Collection</tt> Constructor, asPer theRecommendationinch  the* <tt>Collection</tt> Interface specification.<p> * * the documentation forEach Non-abstract methodinchThisclassDescribes its* ImplementationinchDetail. each ofThese methods may overriddenif* theCollection being implemented admits a more efficient implementation.<p> * *

This class implements the skeleton of the collection interface, and the user inherits the class to implement a set with minimal time.

If we need to implement a simple collection, we just need to rewrite the iterator (), int size (), and add (E O) methods. At the same time, the nature of this collection depends on how we implement it.

List interface

Linear table (list): A finite sequence of 0 or more data elements.

/** * An ordered collection (also known as  a <i>sequence</i>). The user of  This * interface have precise control over  where  in    The  list  each element is  * inserted. The user can access elements by  their integer  Index ( Position in  * the  list ), and  search for  elements in  the  list  .<p> */ 

an ordered set where the user can precisely control where the element is inserted. The user can use the int subscript of the element to get the element and find the element in the list. can have duplicate elements.

Extension methods for the list interface:

    • Add (int index, E Element)
    • AddAll (int index, Collection c)
    • E get (int index)
    • int indexOf (Object o)
    • int lastIndexOf (Object o)
    • Listiterator Listiterator ()
    • Listiterator listiterator (int index)
    • E Remove (int index)
    • default void ReplaceAll (Unaryoperator operator)
    • e Set (int index, e Element)
    • default void Sort (Comparator c)
Listiterator interface
/** * An iterator forLists thatAllows theProgrammer * toTraverse the List inchEither direction, modify * the ListDuring iteration, andObtain theIterator ' s * Current positioninch  the List. A {@code Listiterator} * have no current element; its<i>cursor Position</i> always * liesbetween  theElement thatwould be returned byA call * to{@code Previous ()} and  theElement thatwould be * returned byA call to{@code next ()}. */

A list-designed iterator that allows the user to traverse the list in any direction, modify the list during traversal, and get the current position of the iterator.

Extension methods for Listiterator:

    • Boolean hasprevious ()
    • E Previous ()
    • int Nextindex ()
    • int Previousindex ()
    • void Set (E e)
    • void Add (E e)
Set interface

Set: is a series of discrete data marked with certain correlations or interdependencies.

/** * A Collection that   contains  no duplicate elements. More formally, sets * contain  no pair of  elements & lt;code>e1</code> and  <code>e2</code> such that  * <code>e1. equals   (E2) </code>, and  at  most one null element. As implied by  * its  name , this interface models the  Mathematical <i>set  </i> abstraction. */

A collection that does not contain duplicate elements. the so-called non-repetition refers to the inability to have two elements e1.equals (E2) and at most one null element.

The set interface only contains methods that inherit from collection, and adds duplicate elements that are forbidden to constrain .

The set also adds a stronger contract for the Equals and hashcode operations , allowing the set collection instances to make a meaningful comparison, even if their implementation types are different.

Queue

Queue: is a linear table that allows only one end of an insert operation, while a delete operation at the other end.

/** * A Collection designed forHolding elements Prior toProcessing. * Besides basic {@link java.util.Collection Collection} operations, * Queues provide additional insertion, extraction, andInspection * operations. each ofThese methods existsinchForms:one throws * An exceptionif  theOperation fails, theOther returns a special * value (either {@code null}or{@codefalse}, depending on  the* operation). The latter form of  theInsert operation isDesigned * specifically forUse withcapacity-restricted {@code Queue} * implementations;inchMost implementations, insert operations cannot * fail. */

The interface of the queue , which provides insert, fetch, and retrieve operations outside of collection. There are two forms of these three operations, one of which throws an exception after a failure, and the other returns a specific value (null or FALSE).

Map section

map is a mapping interface in which each element is a key-value key-value pair .

Map interface

The hashing technique establishes a definite correspondencebetween the stored location of the record and its key words , so that each keyword key corresponds to a storage location F (key).

The corresponding relationship f is called the hash function, also known as the hash function.

Hashing is used to store records in a contiguous storage space, which is known as a hash table or hash table.

/** * An object that maps keys to values.  A map cannot contain duplicate keys; * each key can map to at most one value. */

An object that matches the key and value.

The main methods that are included are:

    • int size ()
    • Boolean IsEmpty ()
    • Boolean ContainsKey (Object key)
    • Boolean Containsvalue (Object value)
    • V get (Object key)
    • V Put (K key, V value)
    • V Remove (Object key)
    • Putall (Map m)
    • Clear ()
    • Set KeySet ()
    • Collection VALUES ()
    • EntrySet ()
    • Boolean equals (Object O)
    • int Hashcode ()

The map interface contains a entry interface , which is a key-value pair that encapsulates a map entry. The key value of the entry that can be manipulated by it.

Abstractmap

Implement the skeleton of the map interface to reduce the cost of creating a custom map for your users.

If you want to create a map of your own that can be modified, such as rewrite v put (K key, V value) and the V Remove (Object key) method and implement EntrySet (). iterator ().

SortedMap interface
/** * A {@link Map} thatFurther provides a <em>total ordering</em> on  itsKeys. * The Map isOrdered according to  the{@linkplain Comparable natural * ordering} of  itsKeysor  byA {@link Comparator} typically * provided atSorted map Creation Time. This order isReflected when * iterating Over  theSorted map ' s collection views (returned by  the* {@code EntrySet}, {@code keySet} and{@code Values} methods). * Several additional operations is provided toTake advantage of  the* Ordering. (This interface is  theMap Analogue of{@link SortedSet}.) */

Provides an operation to further sort the key of the map.

Methods of Extension:

    • Comparator Comparator ()
    • K Firstkey ()
    • K Lastkey ()
    • SortedMap Headmap (K tokey)
    • SortedMap SubMap (k Fromkey, K Tokey)
    • SortedMap Tailmap (K fromkey)

Focus on bloggers is an attitude, review Bo Master is a kind of appreciation!!

Finally, you are welcome to pay attention to my public number: Codertopia.

Hidden design routines In 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.