Java For-each Recycling Challenges 2 Cases (advanced use method) _java

Source: Internet
Author: User
Tags int size iterable throw exception concurrentmodificationexception

In Java, the For-each Loop simplifies the traversal of any collection or array, but not every Java programmer understands some of the details of the For-each loop that this article will describe. Other terms released with Java5: releasing alias generics, automatic encapsulation and variable parameters, Java developers use For-each loops more frequently than any other feature, but when asked how the advanced For-each loop works, Or what is the basic need to use collection in a For-each loop, not everyone can answer it.

This tutorial and example is designed to fill this gap by delving into several interesting puzzles in the For-each cycle (to illustrate these issues). Well, no more details, let's look at our first question in the Java5 For-each cycle.


Advanced Cycle Issues 1

Consider the following paragraph that iterates through a user-defined aggregator or collection class code, which prints out what, throws an exception, or a compiler error:

Copy Code code as follows:

Package test;

/**
* Java Class to show how-For-each loop works in Java
*/
public class Foreachtest {

public static void Main (String args[]) {
customcollection<string> mycollection = new customcollection<string> ();
Mycollection.add ("Java");
Mycollection.add ("Scala");
Mycollection.add ("Groovy");

What does this code'll do, print language, throw exception or compile time error
for (String language:mycollection) {
System.out.println (language);
}
}
}

Here's our CustomCollection class, a class with a generic argument, similar to any other collection class, relying on ArrayList and providing a way to add and remove items from collection.

Copy Code code as follows:

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:

The above code will not compile because our CustomCollection class does not implement the Java.lang.Iterable interface, and the compile-time error is as follows:

Copy Code code as follows:

Exception in thread ' main ' java.lang.RuntimeException:Uncompilable source Code-for-each not applicable to expression Ty Pe

Required:array or Java.lang.Iterable
Found:test. CustomCollection
At Test. Foreachtest.main (foreachtest.java:24)

An interesting fact to learn from this is that the For-each loop applies only to Java array and collection classes that implement the Iterable interface. And since all the built-in collection classes implement the Java.util.Collection interface and have inherited iterable, this detail is often ignored, which can be declared "public interface" in the collection interface's type Collection extends Iterable "see. So to solve these problems, you can choose to simply let CustomCollection implement the collection interface or inherit Abstractcollection, which is the default universal implementation and shows how to use both abstract classes and interfaces for better flexibility. Now let's look at the second problem with the For-each cycle:


The second challenge to the Java For-each loop:

The following code example throws a Concurrentmodificationexception exception. Here we use standard iterator and For-each loops to iterate through the ArrayList, then delete the elements, and you need to figure out which piece of code will throw Concurrentmodificationexception, why? Please note that the answer may be two, none, or one of them.

Copy Code code as follows:

Package test;

Import java.util.ArrayList;
Import java.util.Collection;
Import Java.util.Iterator;

/**
* Java class to demonstrate inner working the For-each loop in Java
* @author Javin Paul
**/
public class ForEachTest2 {

public static void Main (String args[]) {
collection<string> list = new arraylist<string> ();
List.add ("Android");
List.add ("IPhone");
List.add ("Windows Mobile");

Which Code would throw concurrentmodificationexception, both,
None or one of them

Example 1
iterator<string> ITR = List.iterator ();
while (Itr.hasnext ()) {
String lang = Itr.next ();
List.remove (lang);
}

Example 2
for (String language:list) {
List.remove (language);
}
}
}

About 70% of Java developers say that the first code block throws a Concurrentmodificationexception exception, because we do not use the iterator Remove method to remove elements, but instead use the ArrayList remove ( Method However, not many Java developers will say the same thing about For-each loops, because we don't use iterator here. In fact, the second code fragment also throws a Concurrentmodificationexception exception, which becomes apparent after the first confusion is resolved. Since iterator is used inside the For-each loop to traverse collection, it also calls Iterator.next (), which checks for (element) changes and throws Concurrentmodificationexception. You can learn this from the output below, and after commenting out the first snippet, you'll get the following output when you run the second snippet.

Copy Code code as follows:

Exception in 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)


The above is all about the Java5 For-each cycle. We've seen a lot of problems that Java programmers have when they write code that traverses the collection class, especially when you're traversing collection and deleting elements. Keep in mind that you always use the iterator Remove method when you delete an object from any collection (such as a map, set, or list). Also keep in mind that the For-each cycle is just a syntactic sugar (syntactic sugar) above standard iterator code usage.

The grammatical sugar (syntactic sugar), also translated into sugar-coated grammar, is a term invented by the British computer scientist Peter John Landa-peter J. Landin, which refers to a syntax added to a computer language that has no effect on the function of a language, But more convenient for programmers to use. In general, the use of syntactic sugar can increase the readability of the program, thereby reducing the chance of error in the program code.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.