For each vs for vs while

I wonder what is the best way to implement a for for each loop through an ArrayList or all kinds of List.

Which of the following implementations is the best and why? Or is there a better way?

Thank you for your help.


List values = new ArrayList();

values.add("one"); values.add("two"); values.add("three"); ...

//#0
for(String value : values) { ... }

//#1
for(int i = 0; i < values.size(); i++) { String value = values.get(i); ... }

//#2
for(Iterator it = values.iterator(); it.hasNext(); ) { String value = it.next(); ... }

//#3
Iterator it = values.iterator(); while (it.hasNext()) { String value = (String) it.next(); ... }

+5
source share
4 answers

# 3 has a flaw, since the scope of the iterator itgoes beyond the loop. Other solutions do not have this problem.

# 2 is exactly the same as # 0, except # 0 is more readable and less error prone.

# 1 is (possibly) less effective, as every time it calls through a loop .size().

# 0 is usually better because:

  • this is the shortest
  • it is the least error prone
  • .
  • ( )
+18

- 0. . Enhanced For Loop Syntax Android , .

+2

# 0 , -, # 2 # 3 . .

# 1. , " ". LinkedList, # 1 n ^ 2 : . , , (, ArrayList), # 1 .

+1

OP.

# 1 ( ), . List < > ArrayList < > , get() ( size()) O (1), List-contract.

:

, , get(int) O(1) List. , AFAIK, size() O(1) List java.util. , # 1 List. , , LinkedList, get(int) - O(N), # 1 O(N^2).

ArrayList size(), () . # 1 , ... ArrayList s.

:

  • , , ConcurrentModificationException s. , , javadocs , .

  • # 1 ( ), . , , . , ​​ , .

  • If the modification in case No. 1 is performed by another thread, it is difficult to synchronize properly. The main problem is that get(int)they size()are separate operations. Even if they are individually synchronized, there is nothing to stop another thread from changing the list between calls sizeand get.

In short, iterating a list that changes at the same time is complicated and should be avoided ... unless you really know what you are doing.

+1
source

All Articles