List vs List iterator

后端 未结 6 1033
清酒与你
清酒与你 2021-01-06 02:51

I have one list:

List myList = new ArrayList();


To get from this list there are two methods:

1.

<
相关标签:
6条回答
  • 2021-01-06 03:20

    Using an Iterator provides much safer access to the List from outside the defining class as you cannot accidentally override the entire List for example. You can only ever access one element at a time: the top one.

    So the guideline we use is to only use the for each approach inside the defining class and whenever the List needs to be accessed from the outside an iterator has to be used. This also enforces the concept of keeping the logic of how to modify a member inside the class that contains it. All complex operations that are needed outside have to be implemented in public methods inside that class.

    0 讨论(0)
  • 2021-01-06 03:21

    Iterator : It gives you the result when needed and don't gets all the result in-memory

    0 讨论(0)
  • 2021-01-06 03:24

    The first one is what you call an "enhanced for loop" which was introduced in JDK 1.5+

    It is more convenient way of iterating through a list. Also, you do not need to do explicit castings if you are using that.

    From the performance perspective, I don't think there isn't much difference between the two.

    0 讨论(0)
  • 2021-01-06 03:30

    Enhanced for loop used iterator only inside it. So both are same.

    0 讨论(0)
  • 2021-01-06 03:39

    First one is more clear, but if you want to remove elements while visiting the list your only choice is an iterator.

    0 讨论(0)
  • 2021-01-06 03:43

    They do the same thing - the enhanced for loop is just syntactic sugar for the longhand version (for iterables; for arrays it's slightly different). Unless you need the iterator explicitly (e.g. to call remove()) I'd use the first version.

    See section 14.14.2 of the Java Language Specification for more details of the exact transformation performed by the compiler.

    0 讨论(0)
提交回复
热议问题