What is the difference between different for loops in Java? -


java has different for-loops walk through list. example:

public void mymethod(list list) {     (int = 0; <= list.size(); i++) {         ...     } } 

or, can write this:

public void mymethod(list list) {     (string obj : list) {         ...     } } 

or, can use list iterator:

public void mymethod(list list) {     iterator<string> iterator = list.iterator();     while (iterator.hasnext()) {         ...     }  } 

which 1 best , prevents nullpointerexceptions without more code?

your second variant best (and it's equivalent third, less verbose). reason it's superior because you're looping via iterator opposed calling get() multiple times, have first variant. linkedlists, instance, get() o(n) operation, meaning first snippet o(n2) whereas second o(n).

in case of null, 3 variants throw nullpointerexception; should check null beforehand (or ensure list can never null).


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -