The difference between iterator, foreach and for based on java

Table of contents

1. Condition differences

2. Differences in parameter types

3. Differences in usage

4. Code Analysis

4.1 for loop

4.2 forEach

4.3 iterator traversal

1. Condition differences

  • for needs to know the size of the collection or array, and it needs to be ordered, otherwise it cannot be traversed;
  • Neither foreach nor iterator need to know the size of the collection or array, they both get each element in the collection and process it;

2. Differences in parameter types

  • Both for and foreach need to know the type of the collection first, even the type of the elements in the collection, that is, the internal members need to be accessed, and the state cannot be realized;
  • Iterator is an interface type, it does not care about the type of the collection or array, and it can modify and delete the elements of the collection at any time.

When we need to iterate over different collections, we just need to pass the collection’s iterator. This is the benefit of an iterator, which does not contain any type information about the sequence it traverses, and can decouple the operation of traversing the sequence from the underlying structure of the sequence.
Iterators unify access to containers. This is also the best embodiment of interface decoupling.

3. Differences in usage

  • For loops are generally used to process relatively simple ordered collections or arrays of predictable size.
  • foreach can be used to traverse any collection or array, and the operation is simple and easy to understand, its only disadvantage is that it needs to understand the internal type of the collection.
  • Iterator is the most powerful, it can modify or delete elements inside the collection at any time, and it does not need to know the types of elements and collections. When you need to implement the same traversal method for different containers, iterate The device is the best choice!

4. Code Analysis

4.1 for loop

public static void main(String[] args) throws FileNotFoundException {

        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);

        for(int i = 0; i < list.size(); i++){
            if(list.get(i).equals(3)) list.remove(i);
        }

        System.out.println(list);

    }

print result:

4.2 [forEach]

public static void main(String[] args) throws FileNotFoundException {

        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);

        for(Integer i : list){
            if(i.equals(3)) list.remove(i);
        }

        System.out.println(list);

    }

print result:

4.3 [iterator] traversal

public static void main(String[] args) throws FileNotFoundException {

        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);

        Iterator<Integer> iterator = list.iterator();

        while(iterator.hasNext()){
            Integer i = iterator.next();

            if(i.equals(3)) list.remove(i);
        }

        System.out.println(list);

    }

print result:

Reason:     At the same time as the collection was added, the deletion operation was performed, which caused the inconsistency between modCount and expectedModCount in the list collection, resulting in an exception being thrown. The list is used here and it is single-threaded, which has caused abnormal errors. In the case of [multi-threading , the probability of abnormal errors is higher.]

[Concurrent] containers such as CopyOnWriteArrayList and Collections.synchronizedCollection() can be used to solve such problems.

Leave a Comment

Your email address will not be published. Required fields are marked *