Which is more efficient, a for-each loop, or an iterator?

后端 未结 7 1512
别那么骄傲
别那么骄傲 2020-11-22 16:00

Which is the most efficient way to traverse a collection?

List  a = new ArrayList();
for (Integer integer : a) {
  integer.toSt         


        
7条回答
  •  [愿得一人]
    2020-11-22 16:23

    Iterator is an interface in the Java Collections framework that provides methods to traverse or iterate over a collection.

    Both iterator and for loop acts similar when your motive is to just traverse over a collection to read its elements.

    for-each is just one way to iterate over the Collection.

    For example:

    List messages= new ArrayList<>();
    
    //using for-each loop
    for(String msg: messages){
        System.out.println(msg);
    }
    
    //using iterator 
    Iterator it = messages.iterator();
    while(it.hasNext()){
        String msg = it.next();
        System.out.println(msg);
    }
    

    And for-each loop can be used only on objects implementing the iterator interface.

    Now back to the case of for loop and iterator.

    The difference comes when you try to modify a collection. In this case, iterator is more efficient because of its fail-fast property. ie. it checks for any modification in the structure of underlying collection before iterating over the next element. If there are any modifications found, it will throw the ConcurrentModificationException.

    (Note: This functionality of iterator is only applicable in case of collection classes in java.util package. It is not applicable for concurrent collections as they are fail-safe by nature)

提交回复
热议问题