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

后端 未结 7 1530
别那么骄傲
别那么骄傲 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:39

    The difference isn't in performance, but in capability. When using a reference directly you have more power over explicitly using a type of iterator (e.g. List.iterator() vs. List.listIterator(), although in most cases they return the same implementation). You also have the ability to reference the Iterator in your loop. This allows you to do things like remove items from your collection without getting a ConcurrentModificationException.

    e.g.

    This is ok:

    Set set = new HashSet();
    // add some items to the set
    
    Iterator setIterator = set.iterator();
    while(setIterator.hasNext()){
         Object o = setIterator.next();
         if(o meets some condition){
              setIterator.remove();
         }
    }
    
    
    

    This is not, as it will throw a concurrent modification exception:

    Set set = new HashSet();
    // add some items to the set
    
    for(Object o : set){
         if(o meets some condition){
              set.remove(o);
         }
    }
    
        

    提交回复
    热议问题