What is the best way to iterate over a list

I worked a lot on the collection, but I have little doubt.

I know that we can iterate over a list using an iterator.

Another way is that we can go through as shown below:

for(int i=0; i<list.size(); i++){
   list.get(i);
}

Here I think that there is a problem that every time the list.size () call will build a whole tree, which will affect performance.

I was thinking of another solution as well:

int s = list.size();
for(int i=0; i<s; i++){
  list.get(i);
}

I think this can solve the problem. I am not very subject to flow. I think this should be the right approach or not.

Another way I thought:

for (Object obj; list){

}

With this new loop, I think the compiler again checks the size of the list.

Please give the best solution from this or an alternative effective approach. Thank you for your help.

+4
4

size() . - O (1) , : size() , .

- get(i). O (1) ArrayList, O (n) LinkedList, O (n 2) O (n): get(i) ( ) node i- .

foreach ( ) , , , .

, , Sets. .

+4

:

for (Object obj: list){

}

, java- < 1.5:

for (Iterator it = hs.iterator() ; it.hasNext() ; ){}

. . .size() , .get() ..get() .size() List..get() ArrayList O (1) , O (n)

UPDATE

java 8 :

myList.forEach{ Object elem -> 
 //do something
}
+4

- ( foreach). list.get(i), . ArrayList list.get(i) - O (1), O (n) LinkedList.

, list.size() O (1) .

+1
for (Object obj: list){

}

- , .

forEach Java 8 .

+1

All Articles