Java-9.5 Iterator
In this section, we will discuss some iterators Iterator.
1. Concept
Iterator (cursor) is a software design pattern for programming. It can be accessed over containers (such as linked lists or arrays, the designer does not need to care about the container content.
package com.ray.ch09;import java.util.ArrayList;import java.util.Collection;import java.util.HashSet;import java.util.Iterator;public class Test {public static void Traversal(Collection
collection) {Iterator
it = collection.iterator();while (it.hasNext()) {int rtn = it.next();System.out.println(rtn);}}public static void main(String[] args) {ArrayList
list = new ArrayList
();for (int i = 0; i < 10; i++) {list.add(i);}HashSet
set = new HashSet
();for (int i = 0; i < 10; i++) {set.add(i);}System.out.println(---------list---------);Traversal(list);System.out.println(---------set---------);Traversal(set);}}
From the code above, we can see that using the iterator, whether it is list or set, can reuse the Traversal method, which improves code reusability.
2. Notes
(1) We only need to receive containers, that is, we can operate on each object.
package com.ray.ch09;import java.util.ArrayList;import java.util.Collection;import java.util.Iterator;public class Test {public static void Traversal(Collection
collection) {Iterator
it = collection.iterator();while (it.hasNext()) {Person person = it.next();System.out.println(person.getId());}}public static void main(String[] args) {ArrayList
list = new ArrayList
();for (int i = 0; i < 10; i++) {Person person = new Person();person.setId(i);list.add(person);}Traversal(list);}}class Person {private int id = 0;public int getId() {return id;}public void setId(int id) {this.id = id;}}
From the code above, we can convert the iterator type to the Person type, and then hold the reference of the Person object. Now we can operate on the person object.
(2) Use of the remove () method
Package com. ray. ch09; import java. util. ArrayList; import java. util. Iterator; public class Test {public static void main (String [] args) {ArrayList
List = new ArrayList
(); For (int I = 0; I <10; I ++) {list. add (I);} Iterator
Iterator = list. iterator (); iterator. next (); // if we comment this sentence, an exception iterator. remove () ;}} will be thrown during runtime ();}}
When we use the remove method, we must first use the next method so that the iterator already points to a new object.
Summary: This chapter briefly discusses the concept of the iterator and the corresponding points of attention.