java - what is the best way of iterate a arraylist -


this question has answer here:

i have these 5 way iterate through arraylist , these are

public static void main(string[] argv) {      // create list     list<string> alist = new arraylist<string>();      // add 4 different values list     alist.add("ebay");     alist.add("paypal");     alist.add("google");     alist.add("yahoo");      // iterate via "for loop"     system.out.println("==> loop example.");     (int = 0; < alist.size(); i++) {         system.out.println(alist.get(i));     }      // iterate via "new way loop"     system.out.println("\n==> advance loop example..");     (string temp : alist) {         system.out.println(temp);     }      // iterate via "iterator loop"     system.out.println("\n==> iterator example...");     iterator<string> aiterator = alist.iterator();     while (aiterator.hasnext()) {         system.out.println(aiterator.next());     }      // iterate via "while loop"     system.out.println("\n==> while loop example....");     int = 0;     while (i < alist.size()) {         system.out.println(alist.get(i));         i++;     }      // collection stream() util: returns sequential stream collection source     system.out.println("\n==> collection stream() util....");     alist.foreach((temp) -> {         system.out.println(temp);     }); } 

my question iterating thru of these way same or there difference? if they, best way of doing this, requirement removing element arraylist based on condition.

my requirement removing element arraylist based on condition

if have remove element arraylist while iterating on it, using explicit iterator base way (your 3rd option). use aiterator.remove() remove current element.

the enhanced loop , foreach don't allow remove elements, since don't have index of current element, , if did, removing element inside enhanced loop throw concurrentmodificationexception.

the regular loop , while loop allow remove elements, since have index of current element, should remember decrement index after removing element, since removing element arraylist shifts elements come after element left.


Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -