java - Flow control, implementation replace method List -


directly [http://docs.oracle.com/javase/tutorial/collections/interfaces/list.html]

public static <e> void replace(list<e> list, e val, e newval) {     (listiterator<e> = list.listiterator(); it.hasnext(); )         if (val == null ? it.next() == null : val.equals(it.next()))             it.set(newval); } 

the bit of trickiness in example equality test between val , it.next. need special-case val value of null prevent nullpointerexception.

i wondering why need special-case val value of null prevent nullpointerexception. might understand have safe code prevent nullpointerexception line of code

if (val == null ? it.next() == null : val.equals(it.next())) 

is not related collection iteration, instead val parameter specified in parameters method.

thanks in advance clarification above mentioned.

your reading of going on here absolutely right: "special case" talking related null-checking parameter, not iteration of list.

in fact, move if statement outside loop more efficient less readable solution:

if (val != null) {     (listiterator<e> = list.listiterator(); it.hasnext(); )         if (val.equals(it.next()))             it.set(newval); } else {     (listiterator<e> = list.listiterator(); it.hasnext(); )         if (it.next() == null)             it.set(newval); } 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -