Iterator iterator vs foreach loop
foreword
This blogger will use CSDN to record the experience and knowledge gained and learned on the road of software development and learning. Interested friends can follow the blogger!
Maybe a person walking alone can go very fast, but a group of people walking together can go further! Let us learn from each other on the road of growth, welcome to pay attention!
1. Iterator interface
1. Iterate over collection elements using the Iterator interface
⭕
Iterator
Objects are called iterators (a design pattern) and are mainly used to traverse the elements in aCollection
collection .
⭕ The
GOF
iterator pattern is defined as: providing a way to accesscontainer
each element in a container ( ) object without exposing the internal details of the object. The iterator pattern is for containers. Similar to "conductor on the bus", "flight attendant on the train", "stewardess".
⭕The
Collection
interface inherits thejava.lang.Iterable
interface, and the interface has aiterator()
method, then allCollection
the collection classes that implement the interface have aiterator()
method to return an object that implements theIterator
interface .
⭕
Iterator
is only used to traverse the collection andIterator
does not provide the ability to host objects by itself. If anIterator
object , there must be an iterated collection.
⭕The collection object
iterator()
gets a brand new iterator object every time the method is called, and the default cursor is before the first element of the collection.
2. Methods of the Iterator interface
Note: The test
it.next()
must be called before calling the methodit.hasNext()
. If it is not called and the next record is invalid, a direct callit.next()
will throwNoSuchElementException
an exception.
3. Execution principle of iterator
3.1 Code Demonstration
//hasNext():判断是否还有下一个元素
while(iterator.hasNext()){
//next():①指针下移 ②将下移以后集合位置上的元素返回
System.out.println(iterator.next());
}
3.2 Analysis of code execution process
When executing the
Iterator iterator = coll.iterator();
statement,iterator
the pointer will execute the position marked by ① in the figure below, and then execute theiterator.hasNext()
statement. At this time, it will judge whetheriterator
there is an element in the next position (ie ②) pointed by the pointer, and if so, returntrue
, Otherwise returnfalse
. When the returntrue
result is , then execute theiterator.next()
statementiterator
downward, the pointer at this time is moved down and the element at the set position pointed to by the moved pointer is returned.
4. Iterator interface remove() method
4.1 Code Demonstration
Iterator iter = coll.iterator();//回到起点
while(iter.hasNext()){
Object obj = iter.next();
if(obj.equals("Tom")){
iter.remove();
} }
4.2 Attention
⭕
Iterator
You can delete the elements of the collection, but it is a method of passing the iterator object during the traversal processremove
, not a method of the collection objectremove
.
⭕ If the method has not been called
next()
or thenext()
method the method is called, an exception will be reported if the method is calledremove
again .remove
IllegalStateException
5. Code demo
@Test
public void test1(){
Collection coll = new ArrayList();
coll.add(123);
coll.add(456);
coll.add(new Person("Jerry",20));
coll.add(new String("Tom"));
coll.add(false);
Iterator iterator = coll.iterator();
//方式一:
// System.out.println(iterator.next());
// System.out.println(iterator.next());
// System.out.println(iterator.next());
// System.out.println(iterator.next());
// System.out.println(iterator.next());
// //报异常:NoSuchElementException
// System.out.println(iterator.next());
//方式二:不推荐
// for(int i = 0;i < coll.size();i++){
// System.out.println(iterator.next());
// }
//方式三:推荐
hasNext():判断是否还有下一个元素
while(iterator.hasNext()){
//next():①指针下移 ②将下移以后集合位置上的元素返回
System.out.println(iterator.next());
}
}
@Test
public void test2(){
Collection coll = new ArrayList();
coll.add(123);
coll.add(456);
coll.add(new Person("Jerry",20));
coll.add(new String("Tom"));
coll.add(false);
//错误方式一:
// Iterator iterator = coll.iterator();
// while((iterator.next()) != null){
// System.out.println(iterator.next());
// }
//错误方式二:
//集合对象每次调用iterator()方法都得到一个全新的迭代器对象,默认游标都在集合的第一个元素之前。
while (coll.iterator().hasNext()){
System.out.println(coll.iterator().next());
}
}
//测试Iterator中的remove()
//如果还未调用next()或在上一次调用 next 方法之后已经调用了 remove 方法,
// 再调用remove都会报IllegalStateException。
@Test
public void test3(){
Collection coll = new ArrayList();
coll.add(123);
coll.add(456);
coll.add(new Person("Jerry",20));
coll.add(new String("Tom"));
coll.add(false);
//删除集合中"Tom"
Iterator iterator = coll.iterator();
while (iterator.hasNext()){
// iterator.remove();
Object obj = iterator.next();
if("Tom".equals(obj)){
iterator.remove();
// iterator.remove();
}
}
//遍历集合
iterator = coll.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
2. Foreach loop
1 Overview
⭕
Java 5.0
Providesforeach
loop iteration accessCollection
and arrays.
⭕ The traversal operation does not need to obtain
Collection
the length of the array or to access the elements using the index.
⭕ The underlying call to traverse the collection
Iterator
completes the operation.
⭕
foreach
can also be used to traverse an array.
2. Grammar analysis
3. Code demo
@Test
public void test1(){
Collection coll = new ArrayList();
coll.add(123);
coll.add(456);
coll.add(new Person("Jerry",20));
coll.add(new String("Tom"));
coll.add(false);
//for(集合元素的类型 局部变量 : 集合对象)
//内部仍然调用了迭代器。
for(Object obj : coll){
System.out.println(obj);
}
//123
//456
//Person@621be5d1
//Tom
//false
}
@Test
public void test2(){
int[] arr = new int[]{
1,2,3,4,5,6};
//for(数组元素的类型 局部变量 : 数组对象)
for(int i : arr){
System.out.println(i);
}
//1
//2
//3
//4
//5
//6
}
4. Error prone questions
public class test {
public static void main(String[] args) {
String[] str = new String[5];
for (String myStr : str) {
myStr = "小老师ir";
System.out.println(myStr);
}
//小老师ir
//小老师ir
//小老师ir
//小老师ir
//小老师ir
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
//null
//null
//null
//null
//null
}
}