Java-Iterator iterator and 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

IteratorObjects are called iterators (a design pattern) and are mainly used to traverse the elements in a Collectioncollection .

⭕ The GOFiterator pattern is defined as: providing a way to access containereach 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 Collectioninterface inherits the java.lang.Iterableinterface, and the interface has a iterator()method, then all Collectionthe collection classes that implement the interface have a iterator()method to return an object that implements the Iteratorinterface .

Iteratoris only used to traverse the collection and Iteratordoes not provide the ability to host objects by itself. If an Iteratorobject , 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

insert image description here

Note: The test it.next()must be called before calling the method it.hasNext(). If it is not called and the next record is invalid, a direct call it.next()will throw NoSuchElementExceptionan 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, iteratorthe pointer will execute the position marked by ① in the figure below, and then execute the iterator.hasNext()statement. At this time, it will judge whether iteratorthere is an element in the next position (ie ②) pointed by the pointer, and if so, return true, Otherwise return false. When the return trueresult is , then execute the iterator.next()statement iteratordownward, the pointer at this time is moved down and the element at the set position pointed to by the moved pointer is returned.

insert image description here

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

IteratorYou can delete the elements of the collection, but it is a method of passing the iterator object during the traversal process remove, not a method of the collection object remove.

⭕ If the method has not been called next()or the next()method the method is called, an exception will be reported if the method is called removeagain .removeIllegalStateException

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.0Provides foreachloop iteration access Collectionand arrays.

⭕ The traversal operation does not need to obtain Collectionthe length of the array or to access the elements using the index.

⭕ The underlying call to traverse the collection Iteratorcompletes the operation.

foreachcan also be used to traverse an array.

2. Grammar analysis

insert image description here

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
    }
}

Guess you like

Origin blog.csdn.net/weixin_52533007/article/details/124310033