Java and mode 26-19th-iteration submode

Source: Internet
Author: User
Document directory
  • Source code
  • Source code

  The iteration submode is also called the cursor mode, which is the behavior mode of objects. The iteration submode can sequentially access an element in the aggregation without exposing the internal representation of the aggregation (Internal Representation).

Aggregation and Java Aggregation

  The aggregation of multiple objects is generally called aggregate. A clustering object is a container object that can accommodate a group of objects. Aggregation depends on the abstraction of the aggregation structure, which is complex and diverse. Arrays are the most basic aggregation and are also the basis for designing other Java clustering objects.

Java clustering object is an object that implements the common Java. util. Collection interface and is directly supported by Java. Since version 1.2, Java provides many clustering types, including vector, arraylist, hashset, hashmap, and hashtable. These are examples of Java aggregation.

Structure of the iteration submode

There are two implementation methods for the iteration submode:White Box aggregation and intrinsic IterationAndBlack Boxes are clustered in inner iterations.

White Box aggregation and intrinsic Iteration

  If a clustering interface provides a method that can be used to modify clustering elements, this interface is calledWide Interface.

If the clustering object provides the same interface, that is, the wide interface for all objects, it will certainly meet the requirements of the iteration sub-Object Mode for iteration sub-objects. However, this will destroy the encapsulation of the clustered object. This aggregation that provides wide interfaces is calledWhite Box Aggregation. The aggregation object provides the same wide interface to the outside world, as shown in:

The aggregation implements the iteration logic by itself and provides an appropriate interface to the outside, so that the iteration sub can control the iteration process of the clustering element from the outside. In this way, the iterator only controls a cursor, which is calledCursor iterator). Since iterations are outside the clustering structure, such iterations are also calledExtrinsic iterator).

Now let's take a look at the implementation of the white box clustering and the intrinsic iteration. A white box aggregation interface (called the Traversal method or the traversing method) provides external users with an interface to access their internal elements, so that the external iterator can implement the iteration function through the aggregation Traversal method.

Because the iteration logic is provided by the clustering object itself, such an extra iteration subrole usually only maintains the cursor position of the iteration.

Shows a typical system composed of white box aggregation and intrinsic iterations. In this implementation, the specific iteration subrole is an external class, the specific clustering role provides external interfaces for Traversing clustering elements.

The iteration submode involves the following roles:

● Abstract iteration sub-(iterator) Role: This abstract role defines the interface required to traverse elements.

● Concreteiterator: this role implements the iterator interface and maintains the cursor position during the iteration.

● Aggregate role: This abstract role provides an interface for creating an iterator object.

● Concreteaggregate role: implements the interface for creating iteration subobjects and returns a suitable iteration subinstance.

● Client role: holds a reference to clustering and Its Iterative sub-objects, calls the iterative interface of iterative sub-objects, and may also add or delete clustering elements through iterative sub-operations.

Source code

Abstract aggregation class, which specifies all the interfaces required for specific aggregation. The iteration sub-mode requires that the clustering object must have a factory method, that is, the createiterator () method, to provide external instances of iterative sub-objects.

Package COM. bankht. iterator;/*** @ Author: -AK47 * @ Creation Time: 11:01:00 ** @ Class description: * abstract clustering Angle class, this role specifies all the interfaces required for specific aggregation. The iteration sub-mode requires that the clustering object must have a factory method, * That is, the createiterator () method, to provide external instances of iterative sub-objects. */Public abstract class aggregate {/*** factory method, and create the interface */public abstract iterator createiterator ();}

The aggregation class implements the interface required by the abstract aggregation class, that is, the createiterator () method. In addition, the getelement () method also provides clustering elements to the outside world, while the size () method provides clustering size to the outside world.

Package COM. bankht. iterator;/*** @ Author: -AK47 * @ Creation Time: 11:01:58 ** @ Class description: * Specific clustering Angle class, the createiterator () method is used to implement the interface required by the abstract clustering class. * In addition, The getelement () method also provides clustering elements to the outside world, while the size () method provides clustering size to the outside world. */Public class concreteaggregate extends aggregate {private object [] objarray = NULL;/*** constructor to pass in the aggregate object content */Public concreteaggregate (object [] objarray) {This. objarray = objarray;} @ overridepublic iterator createiterator () {return New concreteiterator (this);}/*** value method: provide the clustering element */public object getelement (INT index) {If (index <objarray. length) {return objarray [Index];} else {return NULL;}/*** Value Method: Provide the size of the aggregation to the outside world */Public int size () {return objarray. length ;}}

Abstract iteration sub-Role

Package COM. bankht. iterator;/*** @ Author: -AK47 * @ Creation Time: 11:03:35, December 29, ** @ Class description: abstract iteration sub-role class */public interface iterator {/*** iteration method: Move to the first element */Public void first ();/*** iteration method: move to the next element */Public void next ();/*** iteration method: whether it is the last element */Public Boolean isdone ();/*** iteration method: return the current element */public object currentitem ();}

 

Specific iteration sub-Role

Package COM. bankht. iterator;/*** @ Author: -AK47 * @ Creation Time: 11:03:59, December 29, ** @ Class description: specific iteration sub-role class */public class concreteiterator implements iterator {// hold the specific aggregation object of the iteration private concreteaggregate aggregate; // internal index, record the index location from the current iteration private int Index = 0; // record the size of the current clustered object private int size = 0; Public concreteiterator (concreteaggregate iterator) {This. enabled = enabled; this. size = large. size (); Index = 0;}/*** iteration method: return the current element */@ overridepublic object currentitem () {return metadata. getelement (INDEX);}/*** iteration method: Move to the first element */@ overridepublic void first () {Index = 0;}/*** iteration method: whether it is the last element */@ overridepublic Boolean isdone () {return (index> = size);}/*** iteration method: move to the next element */@ overridepublic void next () {If (index <size) {index ++ ;}}}

 

Client type

Package COM. bankht. iterator;/*** @ Author: -AK47 * @ Creation Time: 11:04:28 ** @ Class description: client class */public class client {public void operation () {object [] objarray = {"one", "two", "three", "four", "five", "Six "}; // create an aggregate object aggregate = new concreteaggregate (objarray); // cyclically output the iterator it = aggregate value in the aggregate object. createiterator (); While (! It. isdone () {system. out. println (it. currentitem (); it. next () ;}} public static void main (string [] ARGs) {Client client = new client (); client. operation ();}}

In the preceding example, a clustering class instance is created, and the createiterator () method of the clustering object is called to obtain an iterative sub-object. After an iteration sub-instance is obtained, the client starts the iteration process and prints all the clustering elements.

Meanings of intrinsic iterations

A frequently asked question is: Since the white box clustering has provided the Traversal method to the outside world, the client can iterate on its own. Why should we apply the iteration submode, and create an iteration sub-object for iteration?

Of course, the client can iterate on its own, and it does not have to need an iterative sub-object. However, the iteration sub-objects and the iteration mode abstract the iteration process and separate the iteration sub-responsibilities of the client as the iteration consumer from the iteration owner so that the two can evolve independently. When the types of clustering objects change, or the iterative methods change, the iteration sub-layer, as an intermediary layer, can absorb the changing factors to avoid modifying the client or clustering itself.

In addition, if the system needs to iterate on several different clustering objects at the same time, and these clustering objects provide different traversal methods, it makes sense to use the iteration submode and an external iteration sub-object. Different iteration sub-objects with the same iteration interface process clustering objects with different traversal interfaces, so that the system can use a unified iteration interface for all iterations.

 

Black box aggregation and inner iteration

If a clustering interface does not provide a method to modify clustering elements, such an interface is calledNarrow Interface.

Clustering objects provide a wide interface for iterative sub-objects and a narrow interface for other objects. In other words, the internal structure of the clustering object should be made public to the iterative sub-objects so that the iterative sub-objects can have a sufficient understanding of the clustering object and can be iterated. However, clustering objects should avoid providing these methods to other objects, because other objects should perform these operations through iterative sub-objects rather than directly manipulating the clustering objects.

In Java, the method to implement the dual interface is to design the iteration subclass into an internal Member class of the clustering class. In this way, the iterative sub-object can access the internal structure of the clustering object like the internal members of the clustering object. The following provides a schematic implementation to illustrate how the structure of this double interface is generated, and the implementation scheme of iteration sub-mode after the dual interface structure is used. This solution that guarantees the encapsulation of clustering objects and the implementation of iteration sub-functions is calledBlack box Implementation Scheme.

Since the iterator is an internal clustering class, the iterator can freely access the clustering element, so the iterator can implement the iteration function and control the iteration logic of the clustering element on its own. Since iterations are defined within the aggregation structure, such iterations are also calledIntrinsic iterator ).

To illustrate the details of the black box solution, a schematic black box implementation is provided here. In this implementation, the concreteaggregate aggregation class contains an internal Member class concreteiterator, which is the concrete iteration subclass of the abstract iteration sub-interface, at the same time, aggregation does not provide external access to internal elements.

Source code

Abstract aggregation class, which specifies all the interfaces required for specific aggregation. The iteration sub-mode requires that the clustering object must have a factory method, that is, the createiterator () method, to provide external instances of iterative sub-objects.

Public abstract class aggregate {/*** factory method, create the interface */public abstract iterator createiterator ();}

 

Abstract iteration sub-Role

Public interface iterator {/*** iteration method: Move to the first element */Public void first ();/*** iteration method: move to the next element */Public void next ();/*** iteration method: whether it is the last element */Public Boolean isdone ();/*** iteration method: return the current element */public object currentitem ();}

The aggregate role class implements the interface required by the abstract aggregate role, that is, the createiterator () method. In addition, the clustering class has an internal Member class concreteiterator, which implements the interface defined by the abstract iteration sub-role; and the factory method createiterator () the returned instance is the instance of this internal Member class.

Public class concreteaggregate extends aggregate {private object [] objarray = NULL;/*** constructor to pass in the aggregate object content */Public concreteaggregate (object [] objarray) {This. objarray = objarray;} @ override public iterator createiterator () {return New concreteiterator ();}/*** internal Member class, specific iteration subclass */private class concreteiterator implements iterator {// internal index, record the index location from the current iteration private int Index = 0; // record the size of the current clustered object private int size = 0;/*** constructor */Public concreteiterator () {This. size = objarray. length; Index = 0;}/*** iteration method: return the current element */@ override public object currentitem () {return objarray [Index];} /*** iteration method: Move to the first element */@ override public void first () {Index = 0;}/*** iteration method: whether it is the last element */@ override public Boolean isdone () {return (index> = size);}/*** iteration method: move to the next element */@ override public void next () {If (index <size) {index ++ ;}}}}

Client type

Public class client {public void operation () {object [] objarray = {"one", "two", "three", "four", "five ", "Six"}; // create the aggregate object aggregate = new concreteaggregate (objarray); // cyclically output the iterator it = aggregate value in the aggregate object. createiterator (); While (! It. isdone () {system. out. println (it. currentitem (); it. next () ;}} public static void main (string [] ARGs) {Client client = new client (); client. operation ();}}

 

In the preceding example, a clustering class instance is created, and the createiterator () method of the clustering object is called to obtain an iterative sub-object. After an iteration sub-instance is obtained, the client starts the iteration process and prints all the clustering elements.

Active iteration and passive Iteration

Active iteration and passive iteration are also called external iteration and internal iteration.

The so-called active (external) iterator refers to the step in which the client controls the next element of iteration. The client will obviously call iteration methods such as next () of the iterator, in the traversal process.

Passive (internal) iterations refer to the steps by the iterator itself to control the next element of the iteration. Therefore, if you want to complete the work in the iteration process, the client needs to pass the operation to the iterator. The iterator will execute this operation on each element during iteration, similar to Java callback.

Generally, external iterators are more flexible than internal iterators. Therefore, most of our common implementations are active iterators.

Static and Dynamic iterations

● A static iteration is created by a clustered object and holds a snapshot of the clustered object. After the snapshot is generated, the content of the snapshot does not change. The client can continue to modify the original clustering content, but the iterative sub-object does not reflect the new clustering changes.

The benefit of static iterations is its security and simplicity. In other words, static iterations are easy to implement and are not prone to errors. However, since the static iteration child copies the original aggregation, its short point is the consumption of time and memory resources.

● The dynamic iteration sub-statement is completely opposite to the static iteration sub-statement. After the iteration sub-statement is generated, the iteration sub-statement maintains reference to the clustering element. Therefore, any modification to the original clustering content will be reflected on the iterative sub-object.

Complete Dynamic iterations are not easy to implement, but simplified dynamic iterations are not difficult to implement. The iterations most Java designers encounter are such simplified dynamic iterations. To illustrate what is a simplified dynamic iterator, we need to introduce a new concept:Fail fast.

Fail fast

If the computing environment of an algorithm changes after it starts, and the algorithm cannot make necessary adjustments, the algorithm should immediately send a fault signal. This is what fail fast means.

If the elements of the clustering object change in the iteration process of a dynamic iteration sub-iteration, the iteration process will be affected and cannot be customized. At this time, the iterator should immediately throw an exception. This iteration is the iteration that implements the Fail fast function.

Use of Fail fast in Java Aggregation

JAVA supports the iteration submode by using the java. util. iterator interface. The collection interface requires the iterator () method. This method returns an iterator-type object when calling. As a sub-type of the collection interface, itr is the internal Member class of the abstractlist class that implements the iterator interface.

The source code of the itr class is as follows:

private class Itr implements Iterator<E> {        /**         * Index of element to be returned by subsequent call to next.         */        int cursor = 0;        /**         * Index of element returned by most recent call to next or         * previous.  Reset to -1 if this element is deleted by a call         * to remove.         */        int lastRet = -1;        /**         * The modCount value that the iterator believes that the backing         * List should have.  If this expectation is violated, the iterator         * has detected concurrent modification.         */        int expectedModCount = modCount;        public boolean hasNext() {                return cursor != size();        }        public E next() {                checkForComodification();            try {            E next = get(cursor);            lastRet = cursor++;            return next;            } catch (IndexOutOfBoundsException e) {            checkForComodification();            throw new NoSuchElementException();            }        }        public void remove() {            if (lastRet == -1)            throw new IllegalStateException();                checkForComodification();            try {            AbstractList.this.remove(lastRet);            if (lastRet < cursor)                cursor--;            lastRet = -1;            expectedModCount = modCount;            } catch (IndexOutOfBoundsException e) {            throw new ConcurrentModificationException();            }        }        final void checkForComodification() {            if (modCount != expectedModCount)            throw new ConcurrentModificationException();        }    }

 

From the source code of the itr class, we can see that the checkforcomodification () method checks whether the aggregated content has been directly modified by the outside world (not by the method provided by the iterator ). If the aggregated content is directly modified after the iteration starts, the concurrentmodificationexception () exception is thrown immediately.

That is to say, the aggregactlist. itr iterator is a fail fast iterator.

Advantages of iteration submode

(1) iteration submode simplifies clustering interfaces. The iterator has a traversal interface, so that the aggregation interface does not have to have a traversal interface.

(2) Each clustering object can have one or more iteration sub-objects. The iteration status of each iteration sub-object can be independent of each other. Therefore, a clustering object can have several iterations at the same time.

(3) Since Traversal Algorithms are encapsulated in iterative subroles, iterative algorithms can be independent of aggregate role changes.

 

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.