Reputation: 3
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?
Upvotes: 0
Views: 66
Reputation: 1
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;
}
Upvotes: 0
Reputation: 274
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.
Upvotes: 0
Reputation: 21004
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.
Upvotes: 2