From Java 5 onwards, we have a for-each loop for iterating over arsenal and array in Java. For each loop enables you to traverse over collection without maintaining track of index like traditional for loop, or calling hasNext() approach in while loop utilizing Iterator or ListIterator. For-each loop indeed simplified iteration over any Collection or selection in Java, however not every Java programmer is mindful of some advantageous details of the for-each loop, which we will view in this tutorial. Unfavor various other renowned items from Java 5 release alias Generics, Autoboxing,and also variable debates, Java developers tfinish to use for-each loop even more regularly than any kind of various other attribute, however once asked around exactly how does advanced foreach loop works or what is a straightforward necessity of using a Collection in the for-each loop, not everyone ca solution.

You are watching: For-each not applicable to expression type

This tiny tutorial and example aim to bridge that gap by going via some interesting foreach loop puzzles. So, without any even more delay let"s check out our first puzzle on Java 5 for each loop.

Modern for loop Puzzle 1

Consider below code of Iterating over a user-characterized aggregator or repertoire class in Java, what does it will certainly print or will it throw any exception or compile-time error :

package test;/** * Java Class to display how for-each loop functions in Java */public class ForEachTest public static void main(String args<>) CustomCollectionString> myCollection = new CustomCollectionString>(); myCollection.add("Java"); myCollection.add("Scala"); myCollection.add("Groovy"); // What does this code will perform, print language, throw exemption // or compile time error for(String language: myCollection) System.out.println(language);
and right here is our CustomCollection course, It"s parametric generic class, equivalent to any various other Collection course, backed by ArrayList and offers techniques to include and also remove items from Collection.package test;public course CustomCollection personal ArrayList bucket; public CustomCollection() bucket = new ArrayList(); public int size() rerotate bucket.size(); public boolean isEmpty() rerevolve bucket.isEmpty(); public boolean contains(T o) rerotate bucket.contains(o); public boolean add(T e) rerotate bucket.add(e); public boolean remove(T o) rerotate bucket.remove(o); Answer :


Above code will fail to compile bereason our CustomCollection course does not implement java.lang.Iterable interconfront, as shown in listed below compile time error :Exception in thcheck out "main" java.lang.RuntimeException: Uncompilable source code - for-each not applicable to expression form required: variety or java.lang.Iterable found: test.CustomCollection at test.ForEachTest.main( fact to understand is that for-each loop is applicable only to Java variety and Collection classes which implements Iterable interface, and also since all integrated Collection classes implements java.util.Collection interconfront, which already exoften tends Iterable, this information greatly gets unnoticed. You deserve to check out it in form declaration of Collection interface public interface Collection exhas a tendency Iterable. So in order to deal with above issue, you deserve to either simply make CustomCollection implements Collection interconfront or exoften tends AbstractCollection, which is default general objective implementation and shows exactly how to use abstract class and also interconfront together for better versatility. Now let"s watch second puzzle around for-each loop in Java.

2nd For-Each Puzzle in Java

In complying with code example, which block of code will certainly throw ConcurrentModificatoinException in Java. Here we are iterating over ArrayList making use of conventional iterator and also for-each loop and ultimately rerelocating elements too, you need to uncover out which code will certainly throw ConcurrentModificationException and also why? remember answer can be both, none or any kind of one of them, so beware.package test;import java.util.ArrayList;import java.util.Collection;import java.util.Iterator;/** * Java course to demonstrate inner functioning of for-each loop in Java *
writer Javin Paul **/public class ForEachTest2 public static void main(String args<>) Collection list = new ArrayList(); list.add("Android"); list.add("iPhone"); list.add("Windows Mobile"); // Which Code will throw ConcurrentModificationException, both, // none or one of them // instance 1 Iterator itr = list.iterator(); while(itr.hasNext()) String lang =; list.remove(lang); // example 2 for(String language: list) list.remove(language); About 70% Java developers will certainly say that first code block will throw ConcurrentModificatoinExceptionbereason we are not using Iterator"s remove approach for rerelocating elements, instead we are using ArrayList"s remove() technique. But, not many kind of Java developer will say exact same point around for-each loop, bereason we are not making use of Iterator tright here.
In truth, the second code snippet will also throw ConcurrentModificationException, which is rather obvious after solving initially puzzle. Since for-each loop internally offers Iterator to traverse over Collection, it also calls, which checks for modification and also throws ConcurrentModificationException.

See more: "The Minister'S Black Veil," Why Does The Minister Wear The Black Veil ?

You deserve to view this from the complying with output, which you will obtain, when you run second code snippet after commenting on the first one :Exception in thcheck out "main" java.util.ConcurrentModificationException at java.util.AbstractList$Itr.checkForComodification( at java.util.AbstractList$ at test.ForEachTest2.main("s all on this write-up around Java 5 for-each loop
males. We have seen, couple of prevalent mistake Java programmers make, while composing traversing code for Collection class, especially removing facet, while iterating over arsenal. Remember always use Iterator"s rerelocate technique for deleting objects from any type of Collection e.g. Map, Set or List and also save in mind that for-each loop is simply a syntactic sugar over traditional Iterator code idiom.
Byjavin paul

Labels:collections intersee concerns , core java , java collection tutorial , programming , puzzles
Anonymoussaid...Actually for each loop or advance for loop of Java 5 is nothing however a wrapper approximately iterator, e.g. complying with code :for(String s : listOfString) System.out.println(s)is nothing however equal to for(Iterator it = listOfString.iterator(); it.hashNext(); ) String s =; Systme.out.println(s);for each loop though has actually a limitation e.g. you cannot contact remove() mehtod of Iterator bereason no refernece is easily accessible, it's mearely inferred. You deserve to additionally use for each with variety and any type of class which impelments Iterable interface in Java.