The-iterator of Java review

Source: Internet
Author: User

Iterator and collection and the map series are different, the latter two are mainly used to load other objects, iterator is mainly used to traverse collection objects, iterator is also called an iterator,

Iterator must be attached to collection object

Package mypackage;

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

Import myproject.interface_my;

Public class MyCollection {
public static void Main (string[] args) {
Collection collection=new ArrayList ();
Collection.add ("Lee");
Collection.add ("Love You");
System.out.println (Collection.size ());
System.out.println (Collection.contains (7));
Collection.add ("This is a Beautiful Morning");
System.out.println (collection);
System.out.println (collection.tostring ());
System.out.println (Collection.toarray () [1]);
Collection bookscollection=new HashSet ();
Bookscollection.add ("Java");
Bookscollection.add ("PHP");
System.out.println (bookscollection);
Bookscollection.clear ();
Iterator it=collection.iterator ();
while (It.hasnext ()) {
String books= (String) It.next (),
if (Books.equals ("Lee")) {
// The collection element cannot be modified while using the Iterator object, otherwise an exception
Collection.remove (books) will occur;
}
System.out.println ("Shuo:" +books);
}

}
}

Exception in thread "main" java.util.ConcurrentModificationException
At Java.util.arraylist$itr.checkforcomodification (arraylist.java:859)
At Java.util.arraylist$itr.next (arraylist.java:831)
At Mypackage.Mycollection.main (mycollection.java:30)

Iterator uses a fast failure mechanism that throws a concurrentmodificationexception exception as soon as a collection is detected to be modified.

for (Object object:collection) {
String datastring= (String) object;
System.out.println (datastring);
}

The collection collection cannot be modified during a foreach loop, otherwise it is concurrentmodificationexception wrong.

The-iterator of Java review

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.