Detailed tutorial on Iterator
Iterator is a pattern that can separate the traversal behavior of sequence type data structures from the traversed objects. Next, I will share with you the Java Iterator through this article_Compiled by Power Node Java Academy, friends in need For reference
Iterator is a pattern that can separate the traversal behavior of a sequence type data structure from the object being traversed, that is, we do not need to care about what the underlying structure of the sequence looks like. As long as you get this object, you can traverse the interior of this object using an iterator.
1.Iterator
Java provides a specialized iterator Object <
Document definition:
Package java.util; publicinterface Iterator<E> { boolean hasNext();//判断是否存在下一个对象元素 E next(); void remove(); } Package java.util; public interface Iterator<E> { boolean hasNext();//判断是否存在下一个对象元素 E next(); void remove(); }
2. Iterable
Java also provides an Iterable interface. The function of the Iterable interface after implementation is to "return" an iterator. Our commonly used sub-interfaces that implement this interface are: Collection< E>, Deque
The Iterable interface contains an iterator() method that can generate an Iterator, and the Iterable interface is used by foreach to move in the sequence. So if you create any class that implements the Iterable interface, you can use it in the foreach statement.
Document definition:
Package java.lang; import java.util.Iterator; public interface Iterable<T> { Iterator<T> iterator(); }
Document definition:
Package java.lang; import java.util.Iterator; public interface Iterable<T> { Iterator<T> iterator(); }
Simple example of using Iterator
import java.util.*; publicclass TestIterator { public static void main(String[] args) { List list=new ArrayList(); Map map=new HashMap(); for(int i=0;i<10;i++){ list.add(new String("list"+i) ); map.put(i, new String("map"+i)); } Iterator iterList= list.iterator();//List接口实现了Iterable接口 while(iterList.hasNext()){ String strList=(String)iterList.next(); System.out.println(strList.toString()); } Iterator iterMap=map.entrySet().iterator(); while(iterMap.hasNext()){ Map.Entry strMap=(Map.Entry)iterMap.next(); System.out.println(strMap.getValue()); } } }
Simple example of using Iterator
import java.util.*; public class TestIterator { public static void main(String[] args) { List list=new ArrayList(); Map map=new HashMap(); for(int i=0;i<10;i++){ list.add(new String("list"+i) ); map.put(i, new String("map"+i)); } Iterator iterList= list.iterator();//List接口实现了Iterable接口 while(iterList.hasNext()){ String strList=(String)iterList.next(); System.out.println(strList.toString()); } Iterator iterMap=map.entrySet().iterator(); while(iterMap.hasNext()){ Map.Entry strMap=(Map.Entry)iterMap.next(); System.out.println(strMap.getValue()); } } }
The interface Iterator will expand its functions according to the situation in different sub-interfaces, such as the iterator ListIterator for List, which can only be used for access to various List classes. ListIterator can move in both directions. Added methods such as previous().
3. Iterator is paired with generics
Iterator works on any one of the collection classes Implementation classes can return such an Iterator object. Can be applied to any class.
Because the types of objects that can be loaded into collection classes (List, Set, etc.) are uncertain. When taken out from the collection, they are all of the Object class type, which takes time. It will be very troublesome to perform forced conversion. Using generics means telling the collection in advance to determine the type of collection to be loaded, so that it can be used directly without displaying Type conversion. It is very convenient.
4. The relationship between foreach and Iterator
for each is a new addition in jdk5.0loopStructure can be used to process each element in the collection without considering the collection subscript.
The format is as follows
for(variable:collection){ statement; }
Define a variable to temporarily store each element in the collection and execute the corresponding statement (block). Collection must be an arrayor a class object that implements the alterable interface.
The above example uses generics and forEach writing:
import java.util.*; public class TestIterator { public static void main(String[] args) { List<String> list=new ArrayList<String> (); for(int i=0;i<10;i++){ list.add(new String("list"+i) ); } for(String str:list){ System.out.println(str); } }
The above example uses generics and forEach writing:
import java.util.*; public class TestIterator { public static void main(String[] args) { List<String> list=new ArrayList<String> (); for(int i=0;i<10;i++){ list.add(new String("list"+i) ); } for(String str:list){ System.out.println(str); } }
It can be seen that using The advantage of the for each loop statement is that it is more concise and less error-prone. You don't have to worry about the starting and ending values of the subscript. forEach is not a keyword, the keyword is still for, and the statement is implemented by iterator. The biggest difference between them is the remove() method. Generally, the delete and add methods are methods of specific collections, for example:
List list = new ArrayList(); list.add(...); list.remove(...);
但是,如果在循环的过程中调用集合的remove()方法,就会导致循环出错,因为循环过程中list.size()的大小变化了,就导致了错误。 所以,如果想在循环语句中删除集合中的某个元素,就要用迭代器iterator的remove()方法,因为它的remove()方法不仅会删除元素,还会维护一个标志,用来记录目前是不是可删除状态,例如,你不能连续两次调用它的remove()方法,调用之前至少有一次next()方法的调用。forEach就是为了让用iterator循环访问的形式简单,写起来更方便。当然功能不太全,所以但如有删除操作,还是要用它原来的形式。
4 使用for循环与使用迭代器iterator的对比
采用ArrayList对随机访问比较快,而for循环中的get()方法,采用的即是随机访问的方法,因此在ArrayList里,for循环较快
采用LinkedList则是顺序访问比较快,iterator中的next()方法,采用的即是顺序访问的方法,因此在LinkedList里,使用iterator较快。从数据结构角度分析,for循环适合访问顺序结构,可以根据下标快速获取指定元素.而Iterator 适合访问链式结构,因为迭代器是通过next()和Pre()来定位的.可以访问没有顺序的集合.
而使用 Iterator 的好处在于可以使用相同方式去遍历集合中元素,而不用考虑集合类的内部实现(只要它实现了 java.lang.Iterable 接口),如果使用 Iterator 来遍历集合中元素,一旦不再使用 List 转而使用 Set 来组织数据,那遍历元素的代码不用做任何修改,如果使用 for 来遍历,那所有遍历此集合的算法都得做相应调整,因为List有序,Set无序,结构不同,他们的访问算法也不一样.
【相关推荐】
1. Java免费视频教程
2. YMP在线手册
3. JAVA初级入门视频教程
The above is the detailed content of Detailed tutorial on Iterator. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo
