Which of these methods is most effective when I cross the list?

List<T> list = new ArrayList<T>();

1 method:

for(int i = list.length - 1; i >= 0; i--) {
  System.out.println(list.get(i));
}

2 method:

for(T t : list) {
  System.out.println(t);
}

3 method:

Iterator<T> it = list.iterator();     
while(it.hasNext()) {
  System.out.println(it.next());
}
+3
source share
9 answers

Efficiency is unlikely to be significant - of course, it is System.out.printlnmuch more likely to be a bottleneck in your specific example.

The second approach (improved for the loop) is the most readable one. Note that the three approaches do not do the same: the first one will iterate from the end, not from the beginning. Getting the right behavior almost always surpasses a tiny, tiny cue ball faster. The more readable your code is, the more likely it is that you will fix it.

, , , - ( ).

EDIT: , ArrayList<T>.

List<T>, . List<T> . , get, , . , , . , List<T>.

: , , . , , , . ( , , .) , , ... .

, , , RandomAccess.

+12

, . . get (1000000) LinkedList 1000000 , 1000000- . .

, List, , java.util.RandomAccess. , List API .

+5

1 , .

, ListIterator Iterator,

ListIterator<T> it = list.listIterator();
while (it.hasNext()) {
    T t = it.next;
    int index = it.previousIndex();
    System.out.printf("%d => %s%n", index, t);
}

, 3 2, .

, list get(int) iterator next() hasNext() ( , ), ( , 2.)

+5

RandomAccess

java.util.ArrayList RandomAccess, , :

, List, , ( ) . [...] , List , :

for (int i=0, n=list.size(); i < n; i++)
     list.get(i);

, :

for (Iterator i=list.iterator(); i.hasNext(); )
     i.next();

, a List, implements RandomAccess, indexed-get .

, , , LinkedList, . , LinkedList ; .. get LinkedList.

, indexed- get , . , , .


for-each vs Iterator loop

, . for-each , , . for-each , Iterator.

Effective Java 2nd Edition, . 46: for-each for:

for-each, 1.5, , . :

// The preferred idiom for iterating over collections and arrays
for (Element e : elements) {
    doSomething(e);
}

(:), "in". , " e ". , for-each, . , for , .

.

+2

, , , .

.

: , , . . , .

+1

, List. ArrayList . , :

for(int i = 0, n=list.size(); i < n; i++) {
  System.out.println(list.get(i));
}

, ArrayList . objArrayList.get(i), objArrayList.buffArray[i].

. ,

+1

2, - (, iterator.remove()), 3.

, 1, ( List, , ArrayList).

Update: / , ListIterator List, . 1 -, .

0

, ,

0

.

, , -. , Java , , , , .

. LinkedList, ArrayList, , , , , . , LinkedList , ArrayList. ? .

, , , , .

0

Source: https://habr.com/ru/post/1754370/


All Articles