What are the Advantages of Enhanced for loop and Iterator in Java?

后端 未结 12 2501
遥遥无期
遥遥无期 2020-11-27 20:48

can anyone please specify to me what are the advantages of Enhanced for loop and Iterators in java +5 ?

12条回答
  •  一个人的身影
    2020-11-27 21:27

    You can iterate over any collection that's Iterable and also arrays. And the performance difference isn't anything you should be worried about at all.

    Readability is important.

    Prefer this    
    for (String s : listofStrings) 
        {
         ... 
        }
    
    over
    
        for (Iterator iter = listofStrings.iterator(); iter.hasNext(); )
        {
         String s = iter.next();
         ...
        }
    

    Note that if you need to delete elements as you iterate, you need to use Iterator.

    For example,

    List list = getMyListofStrings(); 
    
        for (Iterator iter = list.iterator(); iter.hasNext(); ) 
        {
            String s = iter.next();
            if (someCondition) {
                iter.remove(); 
            }
        }
    

    You can't use for(String s : myList) to delete an element in the list.
    Also note that when iterating through an array, foreach (or enhanced for) can be used only to obtain the elements, you can't modify the elements in the array.
    For more info, see this.

提交回复
热议问题