Daily summary-java-abstractlist-itr and LISTITR implementation

Source: Internet
Author: User

abstractlistAPI Documentation

Abstractlist implements the list interface, and because list inherits from Collection,collection inherits from Iterable. So the list interface contains many methods.

Abstractlist implements the minimal implementation of the list interface.
He is the way to store data randomly, and if you need to use sequential access to the list of stored data, there is a abstractsequentiallist it is a subclass that inherits from Abstractlist, which should be used preferentially in sequential access.

For non-modifiable lists, you only need to overwrite get and size to

For the modified list, you also need to overwrite the set, and if you want the list size to be variable, you need to expand the Add and Remove methods

Like all collection classes, subclasses typically need to implement two constructors with no arguments and parameters

Abstractlist is a byte implementation of the Iterator method. This is different from other abstract collection classes. The iterator get, set, add, and remove methods are implemented.

Source Analysisabstractlist
protectedAbstractList() {    }

First the constructor must be protected.
If public is likely to be called by the outside world, although this class is an abstract class can not be called constructor, but from the implementation of the purpose of abstractlist is to implement a list for programmers to do some work, rather than directly for the construction of objects, Therefore should not be the protected method.

Of course, it can not be private, first of all, the private modifier after the constructor of this class can not be inherited, from this point of view, the constructor of the abstract class can not be modified with private.
Private is usually used to do a singleton mode, specifically to search the singleton mode.

In this case, you want subclasses to be instantiated, and protected is the best and only option.
It is also necessary to note that the constructor in Java, even if it is a protected method, can be turned into a public method by its subclasses. Or this kind of statement is not rigorous, more rigorous point of view should be the base class of constructors and subclasses of the construction and there is not much of a relationship. Unless a subclass calls Super (), the two are essentially independent of each other.

My current understanding is this, if there is a problem to revise later

Itr

The next is the play, which is the iterator implemented by Abstractlist, but before you say the iterator: the Abstractlist iterator actually defines two iterators, one is the iterator itr that implements the iterator interface, The other is an iterator listitr that implements the Listiterator and inherits from the ITR.
And Listitr is actually inherited from the ITR, so that is more clear. An iterator interface ITR is actually a common basic interface, like collection, which itself has its own inheritance system, but the actual official only gives two child of the inheritance sub-interface, one is Listiterator one is primitiveiterator. Here's the one to see.

Another point, I remember before looking at the Java core technology to remember the details of the implementation of the Java iterator, it should be said here. If you want to see more authoritative statements, refer to the Java core technology. The personal view of Java Core technology is quite thorough and clear.

Let's first introduce the basic ITR implementation:
ITR is actually an inner class. Basically there are three interesting parts, from which the three sections also basically describe how iterators are used:

    1. How to determine the position of the current iterator and how to move it?
    2. How do I delete the elements of an iteration, and what are the effects of deleting them?
    3. How can I prevent the interaction between multiple iterators?

1. How to determine the position of the current iterator and how to move it?
Java iterators differ greatly from those of pointer types in C + +. The main difference is two big points.
One is that the Java iterator cannot be randomly accessed, that is, it is not possible to jump to the specified position based on the number entered, and the iterator arrives at any location that needs to be implemented by the next or possibly existing previous method and can only be moved one by one.
The second is that the iterator does not point to an element, but to the element. After the iterator initializes after the number No. 0 element, the iteration is after the last element, and any point in the period is the position between the two elements.

Therefore, the query is usually required before each call to the iterator, using the Hasnext method to determine if it has been iterated to the end, and returns False if the iteration is to the end. If you have already iterated to the tail, you will be forced to run next and throw an exception.

2. How do I delete the elements of an iteration, and what are the effects of deleting them?
Because Java iterators have no way of random access, you can only delete elements that you just skipped if you need to delete them. This also leads to a certain next before each remove. An exception is thrown if the remove is performed two times in a row. Because you don't know which element is being deleted.

3. How can I prevent the interaction between multiple iterators?
When using iterators, it can cause serious problems if an iterator is modifying an element in an iterator that is another iterator. Java uses a counter to ensure that no two iterators modify the object at the same time, and that the specific part waits for the implementation to illustrate. Typically, an iterator that is being accessed throws an exception if the iterator is being accessed and the other iterator is structurally modifying the object. However, if multiple iterators are read-only, you can do so. Of course, you can also customize the changes into multiple read iterators and a write iterator. This can increase the access rate. However, this feature is not implemented in the Abstractlist class, but only provides the basic iterator functionality.

The above illustrates how iterators are used, and here we begin to discuss how iterators are implemented:

 Private  class Itr implements Iterator<E> {        /** * Index of element to being 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 was deleted by a call * to remove. */int Lastret =-1;/** * The Modcount value, the iterator believes that the backing * List should has.         If this expectation are violated, the iterator * has detected concurrent modification. */int expectedmodcount = Modcount; public Boolean hasnext () {returnCursor! = size (); } public E Next () {checkforcomodification ();Try{int i = cursor;                E next = Get (i);                Lastret = i; cursor = i +1;returnNext }Catch(Indexoutofboundsexception e) {checkforcomodification ();Throw NewNosuchelementexception (); }} public void Remove () {if(Lastret <0)Throw NewIllegalStateException (); Checkforcomodification ();Try{abstractlist. This. Remove (Lastret);if(Lastret < cursor) cursor--; Lastret =-1;            Expectedmodcount = Modcount; }Catch(Indexoutofboundsexception e) {Throw NewConcurrentmodificationexception (); }        }Finalvoid Checkforcomodification () {if(Modcount! = expectedmodcount)Throw NewConcurrentmodificationexception (); }    }protectedtransient int modcount =0;

Let's start with an overview. This class is the inner class of private. Because it is an inner class that has the same access rights as internal variables, it has access to all private members of the Abstractlist class, not to mention protected and public, so you can access modcount directly without adding other scope declarations. And because it is private all variables do not need to add a modifier such as private, because it is not possible to access from outside the scope qualifier.

1. How to determine the position of the current iterator and how to move it?
First, for each iterator, three variables are saved. One is the cursor, one is Lastret, the other is expectedmodcount.
The cursor is incremented one time for each call to the next method. and pass the value of the previous cursor to Lastret (for a possible delete operation), returning the first element I just skipped as the return value. The way to get the elements that have just been skipped is to use the Get method of the Abstractlist class.

For how to determine the Hasnext method for iterating to the tail, the value of the cursor and the size of size are used. If the two are equal, it means that the iteration is at the end.

2. How do I delete the elements of an iteration, and what are the effects of deleting them?
The question says three variables in Lastret, saving the coordinates of each skipped element, and if you need to delete it, just call remove. What you need to consider here is why you use AbstractList.this.remove(lastRet); such a sentence.
Such a sentence is certainly well understood to be the use of the abstract remove method. However, it is not used when using the get. And the Get method does not use such a complex sentence. Obviously it is not possible because the ITR class has its own method of the same name, because the signature of the method is different.

One possible explanation is that it's actually AbstractList.this.remove the standard syntax, but why it's used here but get is not used, and I think it might just be because it doesn't want to be misunderstood. However, the get and modcount references to these external classes are not misleading, so a more concise notation is used. But the inner class itself is a relatively trick problem. Many of my personal experience is not enough, if later think of other more reasonable explanation and then revise.

The second requirement is that the program is judged before each deletion of the Lastret bit, and throws an exception if Lastret is-1.
Lastret in both cases becomes-1, one is deleted after completion, one is initialized, two cases can also be summarized as a situation, before the call to remove does not execute next.

The third small problem is the need to determine if the deleted iterator is before the cursor and, if so, the cursor needs to be reduced by one. Actually this is also very interesting. In fact, this should be a one-way iteration, and why it needs to be judged instead of directly minus one. The possible explanation is that there is also a listitr that inherits the ITR, and it contains the possibility of a forward iteration, so how to replace it with an implementation that does not include a forward iteration does not need to be judged. So the wording here is actually dependent on implementation. Of course you can choose to rewrite the Remove method when writing the Listitr method. However after the article can be seen here the implementation is very beautiful without overwriting any method.

3. How can I prevent the interaction between multiple iterators?
To implement non-impact access between multiple iterators, or if an iterator has structural modifications to an object other iterators can immediately detect the problem and throw an exception (that is, the so-called Fail-fast), which is used in this way:
First, save a modcount number for each object that needs to be iterated (this is the ArrayList object). This number is added 1 per iteration when structural modifications are made. In other words, this variable represents the number of times the object is modified, so it needs to be placed outside the ITR class, inside the Abstractlist class. In addition, this variable is transient, which means that there is no need to store it when serializing.
Next, save a expectedmodcount for each iterator to record the number of times the iterator has made structural modifications to the object. This allows the Expectedmodcount and modcount to be compared each time the iterator is in a structural modification, if the two equals indicate that no other iterator has modified the object. If not equal, the iteration is modified to throw an exception immediately.

It should be explained that the iterator implemented here can only have multiple read access, if the appropriate modification can implement multiple reads and a write coexistence situation, but there is no implementation, if you see later will be added.

Listitr

ITR Read the fact that LISTITR there is no special need to explain. Just inherited the inheritance of ITR, and added a few methods personally think there is no particular need to explain. The basic method is similar to the ITR method.

But there's a very interesting question. Why ITR and LISTITR are implemented simultaneously in abstractlist. Because it is obvious that ITR is implementing the iterator interface, it should be implemented in an earlier collection set, according to reason. I've considered two possible causes myself.

The first is actually within the abstract class of the entire Java implementation, which refers directly to several abstract classes that inherit from the collection class. Abstractlist is the only class that implements the ITR. Other abstract classes are not so complex. Therefore, if implemented in the collection class, it is not possible to use the private inner class, which may break the encapsulation. However, if you do not use private, you will not be able to use Listitr to inherit inherited classes from collection. This is going to be a hassle.

The second question is whether the implementation of ITR actually depends on the implementation. For example, if you cannot use GET or remove to delete the specified cursor in a non-addressable place, then the other place just gives the interface to the line does not need to implement, the concrete implementation needs to combine the actual situation to see.

Of course above as a personal guess.

Daily summary-java-abstractlist-itr and LISTITR implementation

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.