Java Enumeration vs Iteration vs ForLoop [closed]

2019-07-25 06:03发布

问题:

What is the difference between (Enumeration, Iterator, Loop) ??

In the following code each example (Enumeration, Iterator, Loop) gets the same output ] but I need to know what is the real difference between them? Is there specific case where i should use one of them and cant use the others? any advantages in one of them over the others?

回答1:

Enumeration VS Iterator

Iterator is mainly used with non Thread safe Collection. Iterator is designed in such a way that it fails whenever concurrent modification are made to the Collections i.e if a collection which is made for single Threaded environment is used in multithreaded environment and changes are made to it by Thread while it is being traversed then the traversing fails.

Enumeration is used only with Thread safe Collection. When such a collection is used in multithreaded environment consistency of the data is guarantee hence Enumeration never fails

For better understanding you should their Internal Working........

A Collection and its Iterator and Enumeration has a stronger HAS-A relation between them i.e Existence of both parties depends upon each other.



回答2:

Regarding Enumation vs Iteration, from the docs:

Iterator takes the place of Enumeration in the Java Collections Framework. Iterators differ from enumerations in two ways: Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. Method names have been improved.



回答3:

If readability is important.

Prefer this

for (String s : listofStrings) 
    {
     ... 
    }

over

for (Iterator<String> 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<String> list = getMyListofStrings(); 

    for (Iterator<String> 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.