Home Java javaTutorial Implementation method of Java collection Iterator iteration

Implementation method of Java collection Iterator iteration

Jan 23, 2017 pm 05:00 PM

We often use the iteration interface provided by JDK to iterate Java collections.

Iterator iterator = list.iterator();
while(iterator.hasNext()){
String string = iterator.next();
//do something
}
Copy after login

In fact, we can simply understand iteration as traversal, which is a standardized method class for traversing all objects in various containers. It is a very typical design pattern. The Iterator pattern is the standard access method for iterating over collection classes. It can abstract access logic from different types of collection classes, thereby avoiding exposing the internal structure of the collection to the client. This is what we do when there are no iterators. As follows:

For arrays we use subscripts to process:

int[] arrays = new int[10];
for(int i = 0 ; i < arrays.length ; i++){
int a = arrays[i];
//do something
}
Copy after login

For ArrayList this is how we process it:

List<String> list = new ArrayList<String>();
for(int i = 0 ; i < list.size() ; i++){
String string = list.get(i);
//do something
}
Copy after login

For these two methods, we always know the internal structure of the collection in advance. The access code and the collection itself are tightly coupled, and the access logic cannot be separated from the collection class and client code. At the same time, each collection corresponds to a traversal method, and client code cannot be reused. In practical applications, it is quite troublesome to integrate the above two sets. So in order to solve the above problems, the Iterator mode was born, which always uses the same logic to traverse the collection. This eliminates the need for the client itself to maintain the internal structure of the collection, and all internal states are maintained by Iterator. The client never deals directly with the collection class. It always controls the Iterator and sends it the "forward", "backward", and "get current element" commands to indirectly traverse the entire collection.

The above is just a brief explanation of the Iterator pattern. Next, let’s take a look at the Iterator interface in Java and see how it is implemented.

1. java.util.Iterator

In Java, Iterator is an interface. It only provides basic rules for iteration. In the JDK, it is defined like this : Iterator for iterating over collection. Iterators replace Enumeration in the Java Collections Framework. There are two differences between iterators and enumerations:

1. Iterators allow the caller to use well-defined semantics to remove elements from the collection pointed to by the iterator during iteration.

2. The method name has been improved.

The interface is defined as follows:

public interface Iterator {
  boolean hasNext();
  Object next();
  void remove();
}
Copy after login

Among them:

Object next(): Returns the element just crossed by the iterator Reference, the return value is Object, which needs to be cast to the type you need

boolean hasNext(): Determine whether there are any accessible elements in the container

void remove(): Delete the element just crossed by the iterator

For us, we generally only need to use the next() and hasNext() methods to complete the iteration. As follows:

for(Iterator it = c.iterator(); it.hasNext(); ) {
  Object o = it.next();
   //do something
}
Copy after login

As explained earlier, Iterator has a great advantage, that is, we do not need to know the internal results of the collection. The internal structure and state of the collection are maintained by Iterator, through a unified method hasNext(), next() to determine and obtain the next element. As for the specific internal implementation, we don’t need to care. But as a qualified programmer, it is very necessary for us to figure out the implementation of Iterator. Let's analyze the source code of ArrayList.

2. Implementation of Iterator of each collection

The following is an analysis of the Iterator implementation of ArrayList. In fact, if we understand the data structure of ArrayList, Hashset, and TreeSet, the internal Implementation, they will also have a good idea of ​​how they implement Iterator. Because the internal implementation of ArrayList uses an array, we only need to record the index of the corresponding position, and the implementation of its method is relatively simple.

2.1. Iterator implementation of ArrayList

In ArrayList, first define an internal class Itr, which implements the Iterator interface, as follows:

private class Itr implements Iterator<E> {
//do something
}
Copy after login

And the iterator() method of ArrayList is implemented:

public Iterator<E> iterator() {
return new Itr();
}
Copy after login

So by using the ArrayList.iterator() method, what is returned is the Itr() inner class, so now we What needs to be concerned about is the implementation of the Itr() internal class:

Three int-type variables are defined inside Itr: cursor, lastRet, and expectedModCount. Where cursor represents the index position of the next element, and lastRet represents the index position of the previous element

int cursor;
int lastRet = -1;
int expectedModCount = modCount;
Copy after login

It can be seen from the definitions of cursor and lastRet that lastRet is always one less than cursor, so hasNext() The implementation method is extremely simple, you only need to determine whether cursor and lastRet are equal.

public boolean hasNext() {
return cursor != size;
}
Copy after login

The implementation of next() is actually relatively simple. Just return the element at the cursor index position, and then modify the cursor and lastRet

public E next() {
checkForComodification();
int i = cursor; //记录索引位置
if (i >= size) //如果获取元素大于集合元素个数,则抛出异常
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1; //cursor + 1
return (E) elementData[lastRet = i]; //lastRet + 1 且返回cursor处元素
}
Copy after login

checkForComodification() 主要用来判断集合的修改次数是否合法,即用来判断遍历过程中集合是否被修改过。modCount 用于记录 ArrayList 集合的修改次数,初始化为 0,,每当集合被修改一次(结构上面的修改,内部update不算),如 add、remove 等方法,modCount + 1,所以如果 modCount 不变,则表示集合内容没有被修改。该机制主要是用于实现 ArrayList 集合的快速失败机制,在 Java 的集合中,较大一部分集合是存在快速失败机制的,这里就不多说,后面会讲到。所以要保证在遍历过程中不出错误,我们就应该保证在遍历过程中不会对集合产生结构上的修改(当然 remove 方法除外),出现了异常错误,我们就应该认真检查程序是否出错而不是 catch 后不做处理。

final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
Copy after login

对于 remove() 方法的是实现,它是调用 ArrayList 本身的 remove() 方法删除 lastRet 位置元素,然后修改 modCount 即可。

public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
Copy after login

以上所述是小编给大家介绍的Java集合Iterator迭代的实现方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对PHP中文网的支持!

更多Java集合Iterator迭代的实现方法相关文章请关注PHP中文网!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to restrict access to specific interfaces of nested H5 pages through OAuth2.0's scope mechanism? How to restrict access to specific interfaces of nested H5 pages through OAuth2.0's scope mechanism? Apr 19, 2025 pm 02:30 PM

How to use OAuth2.0's access_token to achieve control of interface access permissions? In the application of OAuth2.0, how to ensure that the...

In back-end development, how to distinguish the responsibilities of the service layer and the dao layer? In back-end development, how to distinguish the responsibilities of the service layer and the dao layer? Apr 19, 2025 pm 01:51 PM

Discussing the hierarchical architecture in back-end development. In back-end development, hierarchical architecture is a common design pattern, usually including controller, service and dao three layers...

In Java remote debugging, how to correctly obtain constant values ​​on remote servers? In Java remote debugging, how to correctly obtain constant values ​​on remote servers? Apr 19, 2025 pm 01:54 PM

Questions and Answers about constant acquisition in Java Remote Debugging When using Java for remote debugging, many developers may encounter some difficult phenomena. It...

How to choose Java project management tools when learning back-end development? How to choose Java project management tools when learning back-end development? Apr 19, 2025 pm 02:15 PM

Confused with choosing Java project management tools for beginners. For those who are just beginning to learn backend development, choosing the right project management tools is crucial...

Ultimate consistency in distributed systems: how to apply and how to compensate for data inconsistencies? Ultimate consistency in distributed systems: how to apply and how to compensate for data inconsistencies? Apr 19, 2025 pm 02:24 PM

Exploring the application of ultimate consistency in distributed systems Distributed transaction processing has always been a problem in distributed system architecture. To solve the problem...

How to convert names to numbers to implement sorting within groups? How to convert names to numbers to implement sorting within groups? Apr 19, 2025 pm 01:57 PM

How to convert names to numbers to implement sorting within groups? When sorting users in groups, it is often necessary to convert the user's name into numbers so that it can be different...

Why does the Python script not be found when submitting a PyFlink job on YARN? Why does the Python script not be found when submitting a PyFlink job on YARN? Apr 19, 2025 pm 02:06 PM

Analysis of the reason why Python script cannot be found when submitting a PyFlink job on YARN When you try to submit a PyFlink job through YARN, you may encounter...

How to dynamically modify the savePath parameter of @Excel annotation in easypoi when project starts in Java? How to dynamically modify the savePath parameter of @Excel annotation in easypoi when project starts in Java? Apr 19, 2025 pm 02:09 PM

How to dynamically configure the parameters of entity class annotations in Java During the development process, we often encounter the need to dynamically configure the annotation parameters according to different environments...

See all articles