Enhance For Loop Event In Addition To Puzzle Inwards Java

From Java v onwards, nosotros receive got a for-each loop for iterating over collection together with array inwards Java. For each loop allows yous to traverse over collection without keeping rail of index similar traditional for loop, or calling hasNext() method inwards piece loop using Iterator or ListIterator. For-each loop indeed simplified iteration over whatever Collection or array inwards Java, but non every Java programmer is aware of exactly about useful details of for-each loop, which nosotros volition run into inwards this tutorial. Unlike other pop items from Java v liberate alias Generics, Autoboxing and variable arguments, Java developers tend to exercise for-each loop to a greater extent than ofttimes than whatever other feature, but when asked almost how does advanced foreach loop plant or what is basic requirement of using a Collection inwards for-each loop, non everyone tin answer. This pocket-size tutorial together with event aims to span that gap past times going through exactly about interesting foreach loop puzzles. So, without whatever farther delay let's run into our start puzzle on Java v for-each loop.


Advanced for loop Puzzle 1

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

package test;  /**   * Java Class to demo how for-each loop plant inwards Java   */ populace class ForEachTest {           populace 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 whatever other Collection class, backed past times ArrayList together with provides methods to add together together with withdraw 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 origin code - for-each non applicable to human face 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 solely 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 item to a greater extent than ofttimes than non gets unnoticed. You tin run into it inwards type proclamation of Collection interface public interface Collection extends Iterable. So inwards social club to prepare inwards a higher house issue, yous tin either but brand CustomCollection implements Collection interface or extends AbstractCollection, which is default full general role implementation together with shows how to exercise abstract shape together with interface together for improve flexibility. Now let's run into minute puzzle almost 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 criterion iterator together with for-each loop together with later removing elements every bit well, yous demand to uncovering out which code volition throw ConcurrentModificationException and why? holler upwards reply could hold out both, none or whatever 1 of them, together with then beware.

package test;  import java.util.ArrayList; import java.util.Collection; import java.util.Iterator;  /**   * Java shape 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                 // event 1                 Iterator<String> itr = list.iterator();         while(itr.hasNext()){             String lang = itr.next();             list.remove(lang);         }                  // event 2         for(String language: list){             list.remove(language);         }     } }

About 70% Java developers volition nation that start code block volition throw ConcurrentModificatoinException, because nosotros are non using Iterator's withdraw method for removing elements, instead nosotros are using ArrayList's remove() method. But, non many Java developer volition nation same affair almost for-each loop, because nosotros are non using Iterator there. In reality, minute code snippet volition too throw ConcurrentModificationException, which is quite obvious after solving start puzzle. Since for-each loop internally uses Iterator to traverse over Collection, it too call's Iterator.next(), which checks for change together with throws ConcurrentModificationException. You tin run into this from next output, which yous volition get, when yous run minute code snippet after commenting the start 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 postal service almost Java v for-each loop guys. We receive got seen, dyad of mutual error Java programmers make, piece writing traversing code for Collection class, peculiarly  removing element, piece iterating over collection. Remember ever exercise Iterator's withdraw method for deleting objects from whatever Collection e.g. Map, Set or List and proceed inwards take heed that for-each loop is exactly a syntactic carbohydrate over criterion 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 past times Heinz Kabutz

Komentar

Postingan populer dari blog ini

Difference Betwixt Struts Validatorform Vs Validatoractionform - Interview Question

How To Convert Inputstream To Byte Array Inwards Coffee - Two Examples

Difference Betwixt Fileinputstream Together With Filereader Inwards Coffee | Inputstream Vs Reader