Enhance For Loop Event Together With Puzzle Inwards Java

From Java five onwards, nosotros receive got a for-each loop for iterating over collection together with array inwards Java. For each loop allows you lot to traverse over collection without keeping runway of index similar traditional for loop, or calling hasNext() method inwards spell loop using Iterator or ListIterator. For-each loop indeed simplified iteration over whatsoever Collection or array inwards Java, but non every Java programmer is aware of or then useful details of for-each loop, which nosotros volition encounter inwards this tutorial. Unlike other pop items from Java five unloosen alias Generics, Autoboxing and variable arguments, Java developers tend to usage for-each loop to a greater extent than oftentimes than whatsoever other feature, but when asked well-nigh how does advanced foreach loop industrial plant or what is basic requirement of using a Collection inwards for-each loop, non everyone tin answer. This small-scale tutorial together with instance aims to span that gap yesteryear going through or then interesting foreach loop puzzles. So, without whatsoever farther delay let's encounter our kickoff puzzle on Java five for-each loop.


Advanced for loop Puzzle 1

Consider below code of Iterating over a user defined aggregator or collection degree inwards Java, what does it volition impress or volition it throw whatsoever exception or compile fourth dimension error :

package test;  /**   * Java Class to present how for-each loop industrial plant inwards Java   */ world class ForEachTest {           world static void main(String args[]){         CustomCollection<String> myCollection = new CustomCollection<String>();         myCollection.add("Java");         myCollection.add("Scala");         myCollection.add("Groovy");                 //What does this code volition do, impress language, throw exception or compile fourth dimension error         for(String language: myCollection){             System.out.println(language);         }     } }


together with hither is our CustomCollection class, It's parametric generic class, similar to whatsoever other Collection class, backed yesteryear ArrayList together with provides methods to add together together with take items from Collection.

package test;  public class CustomCollection<T>{     private ArrayList<T> bucket;         public CustomCollection(){         bucket = new ArrayList();     }      public int size() {         return bucket.size();     }      public boolean isEmpty() {         return bucket.isEmpty();     }      public boolean contains(T o) {         return bucket.contains(o);     }         public boolean add(T e) {         return bucket.add(e);     }          public boolean remove(T o) {         return bucket.remove(o);     }        }

Answer : 
each loop for iterating over collection together with array inwards Java Enhance For Loop Example together with Puzzle inwards Java
Above code volition neglect to compile because our CustomCollection class doesn't implement java.lang.Iterable interface, every bit shown inwards below compile fourth dimension error :

Exception inwards thread "main" java.lang.RuntimeException: Uncompilable beginning code - for-each non applicable to aspect type

  required: array or java.lang.Iterable
  found:    test.CustomCollection
        at test.ForEachTest.main(ForEachTest.java:24)

Interesting fact to know is that for-each loop is applicable exclusively to Java array together with Collection classes which implements Iterable interface, together with since all built-in Collection classes implements java.util.Collection interface, which already extends Iterable, this particular generally gets unnoticed. You tin encounter it inwards type announcement of Collection interface public interface Collection extends Iterable. So inwards club to gear upwardly higher upwardly issue, you lot tin either precisely brand CustomCollection implements Collection interface or extends AbstractCollection, which is default full general role implementation together with shows how to usage abstract degree together with interface together for meliorate flexibility. Now let's encounter instant puzzle well-nigh for-each loop inwards Java.

Second For-Each Puzzle inwards Java

In next code example, which block of code volition throw ConcurrentModificatoinException in Java. Here nosotros are iterating over ArrayList using measure iterator together with for-each loop together with afterward removing elements every bit well, you lot demand to detect out which code volition throw ConcurrentModificationException and why? think reply could live on both, none or whatsoever 1 of them, then beware.

package test;  import java.util.ArrayList; import java.util.Collection; import java.util.Iterator;  /**   * Java degree to demonstrate inner working of for-each loop inwards Java   * @author Javin Paul   **/ public class ForEachTest2 {           public static void main(String args[]){         Collection<String> listing = new ArrayList<String>();         list.add("Android");         list.add("iPhone");         list.add("Windows Mobile");                 // Which Code volition throw ConcurrentModificationException, both, 
        // none or 1 of them                 // instance 1                 Iterator<String> itr = list.iterator();         while(itr.hasNext()){             String lang = itr.next();             list.remove(lang);         }                  // instance 2         for(String language: list){             list.remove(language);         }     } }

About 70% Java developers volition tell that kickoff code block volition throw ConcurrentModificatoinException, because nosotros are non using Iterator's take method for removing elements, instead nosotros are using ArrayList's remove() method. But, non many Java developer volition tell same affair well-nigh for-each loop, because nosotros are non using Iterator there. In reality, instant code snippet volition too throw ConcurrentModificationException, which is quite obvious after solving kickoff puzzle. Since for-each loop internally uses Iterator to traverse over Collection, it too call's Iterator.next(), which checks for alteration together with throws ConcurrentModificationException. You tin encounter this from next output, which you lot volition get, when you lot run instant code snippet after commenting the kickoff 1 :

Exception inwards thread "main" java.util.ConcurrentModificationException
        at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
        at java.util.AbstractList$Itr.next(AbstractList.java:343)
        at test.ForEachTest2.main(ForEachTest2.java:34)

That's all on this post service well-nigh Java five for-each loop guys. We receive got seen, duad of mutual error Java programmers make, spell writing traversing code for Collection class, specially  removing element, spell iterating over collection. Remember ever usage Iterator's take method for deleting objects from whatsoever Collection e.g. Map, Set or List and continue inwards heed that for-each loop is precisely a syntactic saccharide over measure Iterator code idiom.

Further Learning
Java In-Depth: Become a Complete Java Engineer
Java Fundamentals: Collections
Data Structures together with Algorithms: Deep Dive Using Java
Algorithms together with Data Structures - Part 1 together with ii
Data Structures inwards Java ix yesteryear Heinz Kabutz

0 Response to "Enhance For Loop Event Together With Puzzle Inwards Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel