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 1Consider 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(ForEachTest.java:24)Interesting 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 JavaIn 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 = itr.next(); 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 Iterator.next(), 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(AbstractList.java:372) at java.util.AbstractList$Itr.next(AbstractList.java:343) at test.ForEachTest2.main(ForEachTest2.java:34)That"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.
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 = it.next(); 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.