About     Search     Feed

Nilesh D Kapadia


Music     Twitter     Github

Performance of using Iterator with List

Using an Iterator to iterate over a List is not always faster than using get(i). If you don’t know what implementation of List you are getting at compile time, you can use a block of code like this to choose the best type of iteration at runtime:

	if(list instanceof RandomAccess) {<br>
	    for (int i=0, n=list.size(); i < n; i++)<br>
	         list.get(i);		    <br>
	} else {<br>
	    for (Iterator i=list.iterator(); i.hasNext(); )<br>
	         i.next();		    <br>
	}<br>

© 2013 Nilesh D Kapadia