Monday, February 21, 2011

The Correct Fashion To Take Away Objects Spell Iterating Over Arraylist Inwards Coffee - Example Tutorial

One of the mutual problems many Java Programmers facial expression upwards is to remove elements piece iterating over ArrayList inwards Java because the intuitive solution doesn't work, e.g., y'all only cannot acquire through an ArrayList using a for loop as well as take an chemical portion depending upon only about condition. Even though java.util.ArrayList provides the remove() methods, e.g. remove (int index) as well as remove (Object element), y'all cannot role them to take items piece iterating over ArrayList inwards Java because they volition throw ConcurrentModificationException if called during iteration. The correct agency to take objects from ArrayList piece iterating over it is past times using the Iterator's remove() method.

When y'all role iterator's remove() method, ConcurrentModfiicationException is non thrown. Because it too updates the counters as well as variables used past times Iterator similar modCount, which indicates that alteration is done past times the Iterator itself as well as non somewhere around.

In this article, I'll present y'all an instance of both ways as well as how they operate inwards Java. You'll too acquire a petty fight nearly java.util.ConcurrentModificationException, which is a mutual occupation for non-concurrent collection classes similar ArrayList or HashMap.

Though, if y'all are solely novel to Java as well as coming from a non-programming background, I advise y'all to commencement acquire through a comprehensive Java class similar The Complete Java MasterClass instead of learning from arbitrary articles.

The class provides structured learning, which is both efficient as well as plant dandy for beginners. Once y'all know the fundamentals, y'all tin acquire whatever theme past times reading a weblog postal service or private tutorial, they volition brand to a greater extent than feel past times thus also.





1. ArrayList remove() method Example

Now, let's come across an instance of removing elements from ArrayList piece looping using for() loop as well as ArrayList.remove() method, which is wrong, as well as the plan volition throw ConcurrentModificationExcetpion upon execution.

import java.util.ArrayList; import java.util.List;  /*  * Java Program to take an chemical portion piece iterating over ArrayList  */  public class Main {    public static void main(String[] args) throws Exception {      List<String> loans = new ArrayList<>();     loans.add("personal loan");     loans.add("home loan");     loans.add("auto loan");     loans.add("credit occupation loan");     loans.add("mortgage loan");     loans.add("gold loan");      // printing ArrayList earlier removing whatever element     System.out.println(loans);      // removing chemical portion using ArrayList's take method during iteration     // This volition throw ConcurrentModification      for (String loan : loans) {       if (loan.equals("personal loan")) {         loans.remove(loan);       }     }      // printing ArrayList subsequently removing an element     System.out.println(loans);   }  }

Output
Exception inwards thread "main" [personal loan, abode loan, car loan, credit occupation loan, mortgage loan, gilt loan]
java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at Main.main(Main.java:26)


Some of y'all may wonder that nosotros are getting ConcurrentModificationException because nosotros are non using the Iterator, but that's non true, fifty-fifty if y'all role Iterator y'all volition acquire java.util.ConcurrentModificationException every bit long every bit y'all volition role ArrayList's remove() method for removing chemical portion piece iterationg every bit shown inwards next example:

Iterator<String> itr = loans.iterator();     piece (itr.hasNext()) {       String loan = itr.next();       if (loan.equals("personal loan")) {         loans.remove(loan);       }     }


Exception inwards thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at Main.main(Main.java:29)


In guild to gain the higher upwards code, you only take to take the loans.remove(loan) alongside the itr.remove() method, which is explained inwards the side past times side example. Though, if y'all desire to know to a greater extent than nearly Iterator as well as inwards full general Java Collection Framework, which tin experience daunting sometimes, I advise y'all acquire through iterating over it.

import java.util.ArrayList;
import java.util.Iterator; import java.util.List;  /*  * Java Program to take an chemical portion piece iterating over ArrayList  */  public class Main {    public static void main(String[] args) throws Exception {      List<String> loans = new ArrayList<>();     loans.add("personal loan");     loans.add("home loan");     loans.add("auto loan");     loans.add("credit occupation loan");     loans.add("mortgage loan");     loans.add("gold loan");      // printing ArrayList earlier removing whatever element     System.out.println(loans);      // removing chemical portion using ArrayList's take method during iteration     // This volition throw ConcurrentModification      Iterator<String> itr = loans.iterator();     while (itr.hasNext()) {       String loan = itr.next();       if (loan.equals("personal loan")) {         itr.remove();       }     }      // printing ArrayList subsequently removing an element     System.out.println(loans);   }  }
 Output
[personal loan, abode loan, car loan, credit occupation loan, mortgage loan, gilt loan]
[home loan, car loan, credit occupation loan, mortgage loan, gilt loan]

From the output, y'all tin come across that the "personal loan" chemical portion is removed from the ArrayList. The size of the ArrayList is too reduced past times one, as well as at that topographic point is no ConcurrentModficiationException inwards the code.


That's all nearly how to take elements piece iterating over ArrayList inwards Java. As I accept said that if y'all role ArrayList's remove() method like remove(int index) or remove(Object obj) piece iterating over ArrayList, thus a ConcurrentModfiicationException volition hold out thrown. You tin avoid that past times using Iterator's remove() method, which removes the electrical flow object inwards the iteration.

Further Learning
The Complete Java Masterclass
tutorial)
  • How to gain as well as initialize ArrayList inwards the same line? (example)
  • Difference betwixt ArrayList as well as HashSet inwards Java? (answer)
  • Difference betwixt an Array as well as ArrayList inwards Java? (answer)
  • How to opposite an ArrayList inwards Java? (example)
  • How to loop through an ArrayList inwards Java? (tutorial)
  • How to synchronize an ArrayList inwards Java? (read)
  • When to role ArrayList over LinkedList inwards Java? (answer)
  • Difference betwixt ArrayList as well as HashMap inwards Java? (answer)
  • Difference betwixt ArrayList as well as Vector inwards Java? (answer)
  • How to variety an ArrayList inwards descending guild inwards Java? (read)
  • How to acquire a sublist from ArrayList inwards Java? (example)
  • How to convert CSV String to ArrayList inwards Java? (tutorial)

  • Thanks for reading this article thus far. If y'all similar this article, thus delight percentage it alongside your friends as well as colleagues. If y'all accept whatever questions or feedback, thus delight drib a note. If y'all like, y'all tin too follow me on Twitter, my id is @javinpaul.


    No comments:

    Post a Comment