0

I hava a List,when I traversed it, this writing code

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

and this writing code

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

Which is better,why?

Godream
  • 3
  • 1

3 Answers3

2

Since you are looping over a collection, use the for-each...

for(Object o : list)
{
    //treatment...
}

As for the difference between those you posted, I'm pretty sure the JVM will optimize it for you anyway.

Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
0

It doesn't make any difference. list.size() does not need to calculate

/**
 * Returns the number of elements in this list.
 *
 * @return the number of elements in this list
 */
public int size() {
    return size;
}
red1ynx
  • 3,639
  • 1
  • 18
  • 23
isea
  • 1
  • If you use ArrayList, fori is the fastest method. If you use LinkedList, foriter is the fastest method. – isea Sep 11 '14 at 02:18
0

To add a point to Jean, in the two for loops:

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

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

Lets compare the situations:
Case1:
If the list items are not going to be modified, that is no frequent addition and deletion is done, then the second for loop is better because you take the size of the list and put it in a variable and compare. Whereas in the first loop, every time the size of the list must be computed.
Case2:
If the list items are going to be changed frequently (insertion and deletion is more), then the size of the list being fixed is not a good idea. The size of the list must be computed dynamically through the size() function every time. So in this case, the first for loop is better. If you want to use the second for loop, then after making the changes in the list, recompute the size of the list and again store in n which is an overhead.

subham soni
  • 274
  • 1
  • 5
  • 17